如何使用 PHP 检查一个单词是否包含在另一个字符串中?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1019169/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 00:39:55  来源:igfitidea点击:

How can I check if a word is contained in another string using PHP?

phpstring

提问by Waseem

Pseudo Code

伪代码

text = "I go to school";
word = "to"
if ( word.exist(text) ) {
    return true ;
else {
    return false ;
}

I am looking for a PHP function which returns true if the word exists in the text.

我正在寻找一个 PHP 函数,如果文本中存在该词,它会返回 true。

回答by pix0r

You have a few options depending on your needs. For this simple example, strpos()is probably the simplest and most direct function to use. If you need to do something with the result, you may prefer strstr()or preg_match(). If you need to use a complex pattern instead of a string as your needle, you'll want preg_match().

根据您的需要,您有几个选择。对于这个简单的例子,strpos()可能是最简单、最直接的函数使用。如果您需要对结果做一些事情,您可能更喜欢strstr()preg_match()。如果您需要使用复杂的模式而不是字符串作为您的针,您将需要preg_match().

$needle = "to";
$haystack = "I go to school";

strpos() and stripos()method (stripos() is case insensitive):

strpos() 和 stripos()方法(stripos() 不区分大小写):

if (strpos($haystack, $needle) !== false) echo "Found!";

strstr() and stristr() method(stristr is case insensitive):

strstr() 和 stristr() 方法(stristr 不区分大小写):

if (strstr($haystack, $needle)) echo "Found!";

preg_match method(regular expressions, much more flexible but runs slower):

preg_match 方法(正则表达式,更灵活但运行速度更慢):

if (preg_match("/to/", $haystack)) echo "Found!";

Because you asked for a complete function, this is how you'd put that together (with default values for needle and haystack):

因为你要求一个完整的函数,这就是你把它放在一起的方式(针和干草的默认值):

function match_my_string($needle = 'to', $haystack = 'I go to school') {
  if (strpos($haystack, $needle) !== false) return true;
  else return false;
}

回答by Steve Clay

function hasWord($word, $txt) {
    $patt = "/(?:^|[^a-zA-Z])" . preg_quote($word, '/') . "(?:$|[^a-zA-Z])/i";
    return preg_match($patt, $txt);
}

If $word is "to", this will match:

如果 $word 是“to”,这将匹配:

  • "Listen to Me"
  • "To the moon"
  • "up-to-the-minute"
  • “听我说”
  • “到月球”
  • “最新”

but not:

但不是:

  • "Together"
  • "Into space"
  • “一起”
  • “进入太空”

回答by Jonathan Fingland

use:

用:

return (strpos($text,$word) !== false); //case-sensitive

or

或者

return (stripos($text,$word) !== false); //case-insensitive

回答by jitter

strpos

链轮

<?php
$text = "I go to school";
$word = "to"
$pos = strpos($text, $word);

if ($pos === false) {
    return false;
} else {
    return true;
}
?>

回答by Eineki

回答by ylebre

Another way (besides the strpos examples already given is to use the 'strstr' function:

另一种方法(除了已经给出的 strpos 示例是使用 'strstr' 函数:

if (strstr($haystack, $needle)) {
   return true;
} else {
   return false;
}

回答by manish1706

You can use these string functions,

您可以使用这些字符串函数,

strstr— Find the first occurrence of a string

strstr— 查找第一次出现的字符串

stristr— Case-insensitive strstr()

stristr— 不区分大小写的 strstr()

strrchr— Find the last occurrence of a character in a string

strrchr— 查找字符串中最后一次出现的字符

strpos— Find the position of the first occurrence of a substring in a string

strpos— 查找子字符串在字符串中第一次出现的位置

strpbrk— Search a string for any of a set of characters

strpbrk— 在字符串中搜索一组字符中的任何一个

If that doesn't help then you should use pregregular expression

如果那没有帮助,那么您应该使用preg正则表达式

preg_match— Perform a regular expression match

preg_match— 执行正则表达式匹配

回答by nektobit

str_contains () in PHP 8

PHP 8 中的 str_contains()

https://wiki.php.net/rfc/str_contains

https://wiki.php.net/rfc/str_contains

Less than 25 years later, and here in PHP they added (https://github.com/php/php-src/commit/1668ad7cb17213e67e42994e0c6911e302a3c3c5) a function that checks whether a line is contained in another line.

不到 25 年后,他们在 PHP 中添加了(https://github.com/php/php-src/commit/1668ad7cb17213e67e42994e0c6911e302a3c3c5)一个检查一行是否包含在另一行中的函数。

str_contains (string $ haystack, string $ needle): bool

str_contains (string $ haystack, string $need): bool

str_contains ("abc", "a"); // true
str_contains ("abc", "d"); // false

Of course, this is just the equivalent. strpos ($ haystack, $ needle)! == false but a pleasant trifle.

当然,这只是等价的。strpos($干草堆,$针)!== 错误但令人愉快的小事。

As alternatives to working with strings, there is already symfony / string (https://github.com/symfony/string) or, for example, voku / Stringy (https://github.com/voku/Stringy/).

作为处理字符串的替代方法,已经有 symfony / string ( https://github.com/symfony/string) 或例如 voku / Stringy ( https://github.com/voku/Stringy/)。

回答by acpmasquerade

@mrclay

@mclay

cant' we simply do

不能'我们只是做

"/(?:^|\w+)" . preg_quote($word, '/') . "(?:$|\w+)/i"

so that it either checks starting or whitespace, and ending or whitespace.

以便它检查开始或空白,以及结束或空白。

回答by Otto Vinzent

After searching so many times for a suitable php version, I decide to write my own contains function (with more than one parameter needles) and good to remember.

在多次寻找合适的 php 版本之后,我决定编写自己的 contains 函数(具有多个参数针)并且很好记住。

function contains($str,$contain)
{
    if(stripos($contain,"|") !== false)
        {
        $s = preg_split('/[|]+/i',$contain);
        $len = sizeof($s);
        for($i=0;$i < $len;$i++)
            {
            if(stripos($str,$s[$i]) !== false)
                {
                return(true);
                }
            }
        }
    if(stripos($str,$contain) !== false)
        {
        return(true);
        }
  return(false);
}

Description of php contains:

php的描述包含:

contains($str,$arg)

$str: The string to be searched
$arg: The needle, more arguments divided by '|'

Examples:

例子:

$str = 'green house';
if(contains($str,"green"))
    echo "we have a green house.";
else
    echo "our house isn't green";

$str = 'green, blue, red houses'; 
if(contains($str,"green|red"))
    echo "we have a green or red house.";
else
    echo "we have a blue house.";