如何检查字符串是否包含特定单词?

How do I check if a string contains a specific word?

提问人: 提问时间:12/6/2010 最后编辑:Charles Yeung 更新时间:8/18/2023 访问量:6619725

问:

这个问题的答案是社区的努力。编辑现有答案以改进此帖子。它目前不接受新的答案或交互。

考虑:

$a = 'How are you?';

if ($a contains 'are')
    echo 'true';

假设我有上面的代码,语句的正确写法是什么?if ($a contains 'are')

PHP 包含 字符串匹配

评论


答:

752赞 17 revs, 12 users 33%Elron #1

您可以使用正则表达式,因为与其他用户提到的,与 相比,它更适合单词匹配。检查还将返回 true 字符串,例如:fare、care、stare 等。在正则表达式中,可以通过使用单词边界来避免这些意外匹配。strposstrposare

一个简单的匹配可能如下所示:are

$a = 'How are you?';

if (preg_match('/\bare\b/', $a)) {
    echo 'true';
}

在性能方面,速度大约快了三倍。当我一次进行一百万次比较时,preg_match花了 1.5 秒才能完成,而花了 0.5 秒。strposstrpos

编辑: 为了搜索字符串的任何部分,而不仅仅是逐个单词,我建议使用正则表达式,例如

$a = 'How are you?';
$search = 'are y';
if(preg_match("/{$search}/i", $a)) {
    echo 'true';
}

正则表达式末尾的 将正则表达式更改为不区分大小写,如果您不希望这样做,可以将其省略。i

现在,在某些情况下这可能是非常有问题的,因为$search字符串没有以任何方式进行清理,我的意思是,在某些情况下,它可能无法通过检查,就好像是用户输入一样,他们可以添加一些字符串,这些字符串的行为可能像一些不同的正则表达式......$search

此外,这是一个很棒的工具,用于测试和查看各种正则表达式 Regex101 的解释

要将这两组功能组合成一个多用途函数(包括可选区分大小写的功能),可以使用如下方法:

function FindString($needle,$haystack,$i,$word)
{   // $i should be "" or "i" for case insensitive
    if (strtoupper($word)=="W")
    {   // if $word is "W" then word search instead of string in string search.
        if (preg_match("/\b{$needle}\b/{$i}", $haystack)) 
        {
            return true;
        }
    }
    else
    {
        if(preg_match("/{$needle}/{$i}", $haystack)) 
        {
            return true;
        }
    }
    return false;
    // Put quotes around true and false above to return them as strings instead of as bools/ints.
}

还有一点要记住,\b 不适用于英语以外的其他语言。

对此的解释和解决方案取自这里

\b表示单词的开头或结尾(单词边界)。这 正则表达式将在 Apple Pie 中匹配 Apple,但不会在 菠萝、苹果车或烤苹果。

“咖啡馆”怎么样?我们如何在正则表达式中提取“咖啡馆”一词? 实际上,\bcafé\b 是行不通的。为什么?因为“咖啡馆”包含 非 ASCII 字符:é。\b 不能简单地与 Unicode 一起使用,例如 समुद्र, 감사, месяц 和 😉 .

当您要提取Unicode字符时,应直接 定义表示单词边界的字符。

答案是:(?<=[\s,.:;"']|^)UNICODE_WORD(?=[\s,.:;"']|$)

所以为了在PHP中使用答案,你可以使用这个函数:

function contains($str, array $arr) {
    // Works in Hebrew and any other unicode characters
    // Thanks https://medium.com/@shiba1014/regex-word-boundaries-with-unicode-207794f6e7ed
    // Thanks https://www.phpliveregex.com/
    if (preg_match('/(?<=[\s,.:;"\']|^)' . $word . '(?=[\s,.:;"\']|$)/', $str)) return true;
}

如果你想搜索单词数组,你可以使用这个:

function arrayContainsWord($str, array $arr)
{
    foreach ($arr as $word) {
        // Works in Hebrew and any other unicode characters
        // Thanks https://medium.com/@shiba1014/regex-word-boundaries-with-unicode-207794f6e7ed
        // Thanks https://www.phpliveregex.com/
        if (preg_match('/(?<=[\s,.:;"\']|^)' . $word . '(?=[\s,.:;"\']|$)/', $str)) return true;
    }
    return false;
}

从 PHP 8.0.0 开始,您现在可以使用 str_contains

<?php
    if (str_contains('abc', '')) {
        echo "Checking the existence of the empty string will always"
        return true;
    }

评论

11赞 Breezer 12/6/2010
@Alexander.普鲁托夫,其次,你给我一个-1,而不是问题?来吧,谷歌答案需要 2 秒钟 google.com/......
65赞 SamGoody 11/9/2011
+1 搜索简单字符串是一种可怕的方式,但许多 SO 的访问者正在寻找任何方法来搜索他们自己的任何子字符串,并且提出这个建议很有帮助。甚至 OP 也可能过于简单化——让他知道他的替代方案。
77赞 8/20/2013
从技术上讲,这个问题问的是如何找到单词而不是子字符串。这实际上帮助了我,因为我可以将其与正则表达式单词边界一起使用。替代方案总是有用的。
16赞 albanx 11/6/2014
答案为 +1,@plutov.by 评论为 -1,因为 strpos 只是一个检查,而正则表达式您可以同时检查多个单词,例如:preg_match(/are|you|not/)
7赞 yentsun 2/18/2015
正则表达式应该是最后的手段。应劝阻在琐碎的任务中使用它们。我从多年挖掘坏代码的高度坚持这一点。
8029赞 22 revs, 18 users 41%SeniorDeveloper #2

现在在 PHP 8 中,您可以使用 str_contains 来做到这一点:

if (str_contains('How are you', 'are')) { 
    echo 'true';
}

请注意:如果$needle(要在字符串中搜索的子字符串)为空,则该函数将始终返回 true。str_contains

$haystack = 'Hello';
$needle   = '';

if (str_contains($haystack, $needle)) {
    echo "This returned true!";
}

首先应确保$needle(子字符串)不为空。

$haystack = 'How are you?';
$needle   = '';

if ($needle !== '' && str_contains($haystack, $needle)) {
    echo "This returned true!";
} else {
    echo "This returned false!";
}

输出This returned false!

还值得注意的是,新功能区分大小写。str_contains

$haystack = 'How are you?';
$needle   = 'how';

if ($needle !== '' && str_contains($haystack, $needle)) {
    echo "This returned true!";
} else {
    echo "This returned false!";
}

输出This returned false!

RFC的

PHP 8 之前

您可以使用 strpos() 函数,该函数用于查找一个字符串在另一个字符串中的出现:

$haystack = 'How are you?';
$needle   = 'are';

if (strpos($haystack, $needle) !== false) {
    echo 'true';
}

请注意,使用 是故意的(既不会也不会返回所需的结果); 返回针串在大海捞针串中开始的偏移量,如果找不到针,则返回布尔值。由于 0 是有效的偏移量,而 0 是“假的”,因此我们不能使用更简单的结构,例如 .!== false!= false=== truestrpos()false!strpos($a, 'are')

评论

181赞 jsherk 11/15/2012
@DTest - 嗯,是的,当然它会返回 true,因为字符串包含“are”。如果您专门寻找单词 ARE,那么您需要进行更多检查,例如,检查 A 之前和 E 之后是否有字符或空格。
46赞 Melsi 12/15/2012
上面的评论非常好!我从不使用 != 或 ==,毕竟 !== 和 === 是最好的选择(在我看来),考虑了所有方面(速度、准确性等)。
11赞 Giulio Muscarello 1/6/2013
@jsherk 那么为什么不使用正则表达式呢?像“是”这样的东西。
8赞 Wouter 9/23/2013
至于没有抓住“关心”之类的东西,最好检查一下 (strpos(' ' . strtolower($a) 。' ', ' are ') !== false)
32赞 equazcion 5/6/2014
我倾向于通过始终使用 to test for true 来避免这个问题。从调试的角度来看,我发现当我不必计算连续的等号时,我的大脑浪费了更少的时钟周期来确定行是否正确写入。strpos($a, 'are') > -1
79赞 3 revs, 3 users 55%Haim Evgi #3

查看 strpos()

<?php
$mystring = 'abc';
$findme   = 'a';
$pos = strpos($mystring, $findme);

// Note our use of ===. Simply, == would not work as expected
// because the position of 'a' was the 0th (first) character.
if ($pos === false) {
    echo "The string '$findme' was not found in the string '$mystring'.";
} else {
    echo "The string '$findme' was found in the string '$mystring',";
    echo " and exists at position $pos.";
}
177赞 5 revs, 5 users 74%Jose Vega #4

要确定一个字符串是否包含另一个字符串,您可以使用 PHP 函数 strpos()。

int strpos ( string $haystack , mixed $needle [, int $offset = 0 ] )`
<?php

$haystack = 'how are you';
$needle = 'are';

if (strpos($haystack,$needle) !== false) {
    echo "$haystack contains $needle";
}

?>

谨慎:

如果您要搜索的针在大海捞针的开头,它将返回位置 0,如果您进行比较不起作用,则需要执行=====

符号是一种比较,用于测试左侧的变量/表达式/常量是否与右侧的变量/表达式/常量具有相同的值。==

符号是一种比较,用于查看两个变量/表达式/常量是否相等,是否具有相同的类型 - 即两者都是字符串或都是整数。===AND

使用这种方法的优点之一是每个 PHP 版本都支持此功能,这与 .str_contains()

评论

0赞 Jahirul Islam Mamun 8/8/2020
如果我使用“care”,它的返回也为 true:(
66赞 glutorange #5

如果您的搜索不区分大小写,则使用 strstr() 或 stristr() 将是另一种选择。

评论

9赞 Jo Smo 2/9/2014
php.net/manual/en/function.strstr.php 页面上的注释: 注意:如果您只想确定特定针是否出现在大海捞针中,请改用速度更快且内存占用更少的函数 strpos()。
0赞 Wayne Whitty 6/17/2014
@tastro 在这方面有没有信誉良好的基准?
0赞 Paul Spiegel 3/15/2018
这可能会更慢,但恕我直言,它比丑陋的要优雅得多。PHP确实需要一个函数。strstr($a, 'are')strpos($a, 'are') !== falsestr_contains()
0赞 kurdtpage 1/15/2020
令我大吃一惊的是,这不是公认的答案
300赞 ejunker #6

这里有一个小的实用函数,在这样的情况下很有用

// returns true if $needle is a substring of $haystack
function contains($needle, $haystack)
{
    return strpos($haystack, $needle) !== false;
}

评论

75赞 Xaqq 7/9/2013
@RobinvanBaalen 实际上,它可以提高代码的可读性。此外,反对票应该是针对(非常)糟糕的答案,而不是针对“中立”的答案。
40赞 Brandin 7/25/2013
@RobinvanBaalen函数的定义几乎是为了可读性(传达你正在做的事情的想法)。比较哪个更具可读性:或if ($email->contains("@") && $email->endsWith(".com)) { ...if (strpos($email, "@") !== false && substr($email, -strlen(".com")) == ".com") { ...
3赞 James P. 8/22/2013
@RobinvanBaalen最终规则是要被打破的。否则,人们不会想出更新的创造性做事方式:)。另外,我不得不承认,我很难把注意力集中在 martinfowler.com 之类的事情上。猜猜正确的做法是自己尝试一下,找出最方便的方法。
6赞 Tino 2/21/2014
另一种观点:拥有一个可以轻松包装的实用程序函数可以帮助调试。此外,它还呼吁使用好的优化器来消除生产服务中的这种开销。所以所有的意见都有道理。;)
20赞 Cosmin 6/17/2015
当然,这是有用的。你应该鼓励这样做。如果在 PHP 100 中有一种新的、更快的方法来查找字符串位置,会发生什么?你想改变你调用strpos的所有地方吗?或者您只想更改函数中的包含?
32赞 YashG99 #7

另一种选择是使用 strstr() 函数。像这样:

if (strlen(strstr($haystack,$needle))>0) {
// Needle Found
}

需要注意的一点是:strstr() 函数区分大小写。对于不区分大小写的搜索,请使用 stristr() 函数。

评论

1赞 AKS 9/11/2012
strstr() 如果未找到针,则返回 FALSE。所以没有必要进行 strlen。
43赞 Alan Piralla #8

如果你想避免“虚假”和“真实”的问题,你可以使用substr_count:

if (substr_count($a, 'are') > 0) {
    echo "at least one 'are' is present!";
}

它比 strpos 慢一点,但它避免了比较问题。

评论

0赞 Hafenkranich 2/12/2020
它返回 “你确定吗?”,因为 的位置是falsestrpos0
25赞 Jason OOO #9

下面的函数也可以工作,并且不依赖于任何其他函数;它只使用本机 PHP 字符串操作。就个人而言,我不建议这样做,但您可以看到它是如何工作的:

<?php

if (!function_exists('is_str_contain')) {
  function is_str_contain($string, $keyword)
  {
    if (empty($string) || empty($keyword)) return false;
    $keyword_first_char = $keyword[0];
    $keyword_length = strlen($keyword);
    $string_length = strlen($string);

    // case 1
    if ($string_length < $keyword_length) return false;

    // case 2
    if ($string_length == $keyword_length) {
      if ($string == $keyword) return true;
      else return false;
    }

    // case 3
    if ($keyword_length == 1) {
      for ($i = 0; $i < $string_length; $i++) {

        // Check if keyword's first char == string's first char
        if ($keyword_first_char == $string[$i]) {
          return true;
        }
      }
    }

    // case 4
    if ($keyword_length > 1) {
      for ($i = 0; $i < $string_length; $i++) {
        /*
        the remaining part of the string is equal or greater than the keyword
        */
        if (($string_length + 1 - $i) >= $keyword_length) {

          // Check if keyword's first char == string's first char
          if ($keyword_first_char == $string[$i]) {
            $match = 1;
            for ($j = 1; $j < $keyword_length; $j++) {
              if (($i + $j < $string_length) && $keyword[$j] == $string[$i + $j]) {
                $match++;
              }
              else {
                return false;
              }
            }

            if ($match == $keyword_length) {
              return true;
            }

            // end if first match found
          }

          // end if remaining part
        }
        else {
          return false;
        }

        // end for loop
      }

      // end case4
    }

    return false;
  }
}

测试:

var_dump(is_str_contain("test", "t")); //true
var_dump(is_str_contain("test", "")); //false
var_dump(is_str_contain("test", "test")); //true
var_dump(is_str_contain("test", "testa")); //flase
var_dump(is_str_contain("a----z", "a")); //true
var_dump(is_str_contain("a----z", "z")); //true 
var_dump(is_str_contain("mystringss", "strings")); //true 

评论

14赞 sg3s 9/19/2013
你能告诉我为什么你会使用这样的函数,而strpos是一个完全可行的解决方案吗?...
3赞 Jason OOO 9/20/2013
@sg3s:你说得很对,但是,strpos 也基于类似的东西,而且,我不是为了分享一些知识而发布它给代表的
0赞 Sunny 5/18/2015
上一个var_dump是错误的
1赞 Jason OOO 5/18/2015
@Sunny:是错别字:var_dump(is_str_contain(“mystringss”, “strings”));真
37赞 4 revs, 2 users 88%joan16v #10
if (preg_match('/(are)/', $a)) {
   echo 'true';
}

评论

3赞 Pathros 8/11/2016
我收到以下警告:WARNING preg_match(): Delimiter must not be alphanumeric or backslash
54赞 4 revs, 3 users 75%Shankar Narayana Damodaran #11

使用 strpos() 使用子字符串匹配:

if (strpos($string,$stringToSearch) !== false) {
    echo 'true';
}
21赞 Sadikhasan #12

使用 strstr() 和 stristr() 从字符串中查找单词出现的另一种选择如下所示:

<?php
    $a = 'How are you?';
    if (strstr($a,'are'))  // Case sensitive
        echo 'true';
    if (stristr($a,'are'))  // Case insensitive
        echo 'true';
?>

评论

0赞 Adam Merrifield 4/1/2014
这是倒退的。in 代表不敏感。istristr
23赞 Decebal #13

我遇到了一些麻烦,最后我选择创建自己的解决方案。不使用正则表达式引擎:

function contains($text, $word)
{
    $found = false;
    $spaceArray = explode(' ', $text);

    $nonBreakingSpaceArray = explode(chr(160), $text);

    if (in_array($word, $spaceArray) ||
        in_array($word, $nonBreakingSpaceArray)
       ) {

        $found = true;
    }
    return $found;
 }

您可能会注意到,前面的解决方案不是用作另一个前缀的单词的答案。为了使用您的示例:

$a = 'How are you?';
$b = "a skirt that flares from the waist";
$c = "are";

对于上面的示例,both 和 contains ,但您可能希望函数告诉您 only contains .$a$b$c$a$c

评论

1赞 slownage 3/4/2015
你的意思是:一开始$found = false
1赞 lightbringer 4/15/2015
如果单词与逗号、问号或点链接,您的函数可能无法正常工作。例如,“你所看到的就是你得到的”,你想确定句子中是否有“得到”。请注意“get”旁边的句号。在本例中,函数返回 false。建议使用正则表达式或substr(我认为它无论如何都使用正则表达式)来搜索/替换字符串。
0赞 Decebal 4/16/2015
@lightbringer你的建议大错特错,那么“推荐”对你来说意味着什么?没有至高无上的人会推荐或证明。这是关于在php中使用正则表达式引擎,这是语言本身的一个黑洞,你可能想尝试将正则表达式匹配放在一个循环中,并对结果进行基准测试。
0赞 mickmackusa 7/24/2019
这个答案没有得到很好的证明,并且在许多扩展方案中都失败了。我看不出娱乐这种技术有什么好处。以下是改进的自定义函数和迭代调用: 3v4l.org/E9dfD 我对编辑这个 wiki 没有兴趣,因为我发现它浪费了研究人员的时间。
16赞 3 revs, 2 users 78%Vinod Joshi #14

如果只想检查一个字符串是否包含在另一个字符串中,请不要使用。使用 or 代替,因为它们会更快。(https://www.php.net/preg_matchpreg_match()strpos()strstr())

if (strpos($text, 'string_name') !== false){
   echo 'get the string';
}
 
162赞 FtDRbwLXw6 #15

虽然这些答案中的大多数都会告诉您字符串中是否出现了子字符串,但如果您正在寻找特定单词而不是子字符串,这通常不是您想要的。

有什么区别?子字符串可以出现在其他单词中:

  • “area”开头的“are”
  • “hare”末尾的“are”
  • “票价”中间的“是”

缓解此问题的一种方法是使用正则表达式和单词边界 ():\b

function containsWord($str, $word)
{
    return !!preg_match('#\\b' . preg_quote($word, '#') . '\\b#i', $str);
}

此方法没有上面提到的相同误报,但它确实有一些自己的边缘情况。单词边界与非单词字符 () 匹配,这些字符将是任何不是 、 、 或 .这意味着数字和下划线将被计为单词字符,并且像这样的场景将失败:\Wa-zA-Z0-9_

  • “你在想什么?
  • “lol u dunno wut those are4”中的“are”是什么?

如果你想要比这更准确的东西,你必须开始做英语语法解析,这是一个相当大的蠕虫罐头(无论如何,假设正确使用语法,这并不总是给定的)。

评论

25赞 code_monk 10/12/2014
这应该是规范的答案。因为我们要找的是单词而不是子字符串,所以正则表达式是合适的。我还要补充一点,它匹配两个不匹配的东西,这使得它非常适合在字符串中查找单词:它匹配字符串的开头 () 和字符串的结尾 (\b\W^$)
1赞 Robert Sinclair 6/30/2016
这应该是正确答案..其余的答案将在字符串中找到“are”,例如“do you care”。正如@Dtest所提到的
0赞 Paul 7/6/2016
@RobertSinclair 有那么糟糕吗?如果你问我字符串“do you care”是否包含“are”这个词,我会说“是”。单词“are”显然是该字符串的子字符串。这是一个与“是”是“字符串”
0赞 Robert Sinclair 7/7/2016
@Paulpro尽管 OP 没有指定$a是一个短语,但我很确定它是暗示的。所以他的问题是如何检测短语中的单词。如果一个单词包含一个单词,则不会,我认为这通常无关紧要。
0赞 MetalWeirdo 7/24/2018
@Jimbo它确实有效,您只是缺少“\”3v4l.org/ZRpYi
57赞 RafaSashi #16

对等 SamGoody 和 Lego Stormtroopr 的评论。

如果您正在寻找一种 PHP 算法来根据多个单词的接近度/相关性对搜索结果进行排名 这里有一种仅使用 PHP 生成搜索结果的快速简便的方法:

其他布尔搜索方法(如 strpos())、preg_match()strstr() 或 stristr() )的问题

  1. 无法搜索多个字词
  2. 结果未排名

基于向量空间模型tf-idf(项频率-逆文档频率)的PHP方法:

这听起来很困难,但出乎意料地容易。

如果我们想在一个字符串中搜索多个单词,核心问题是如何为每个单词分配权重?

如果我们能根据字符串对整个字符串的代表性来对字符串中的术语进行加权, 我们可以按与查询最匹配的结果对结果进行排序。

这是向量空间模型的思想,与SQL全文搜索的工作原理相差不远:

function get_corpus_index($corpus = array(), $separator=' ') {

    $dictionary = array();

    $doc_count = array();

    foreach($corpus as $doc_id => $doc) {

        $terms = explode($separator, $doc);

        $doc_count[$doc_id] = count($terms);

        // tf–idf, short for term frequency–inverse document frequency, 
        // according to wikipedia is a numerical statistic that is intended to reflect 
        // how important a word is to a document in a corpus

        foreach($terms as $term) {

            if(!isset($dictionary[$term])) {

                $dictionary[$term] = array('document_frequency' => 0, 'postings' => array());
            }
            if(!isset($dictionary[$term]['postings'][$doc_id])) {

                $dictionary[$term]['document_frequency']++;

                $dictionary[$term]['postings'][$doc_id] = array('term_frequency' => 0);
            }

            $dictionary[$term]['postings'][$doc_id]['term_frequency']++;
        }

        //from http://phpir.com/simple-search-the-vector-space-model/

    }

    return array('doc_count' => $doc_count, 'dictionary' => $dictionary);
}

function get_similar_documents($query='', $corpus=array(), $separator=' '){

    $similar_documents=array();

    if($query!=''&&!empty($corpus)){

        $words=explode($separator,$query);

        $corpus=get_corpus_index($corpus, $separator);

        $doc_count=count($corpus['doc_count']);

        foreach($words as $word) {

            if(isset($corpus['dictionary'][$word])){

                $entry = $corpus['dictionary'][$word];


                foreach($entry['postings'] as $doc_id => $posting) {

                    //get term frequency–inverse document frequency
                    $score=$posting['term_frequency'] * log($doc_count + 1 / $entry['document_frequency'] + 1, 2);

                    if(isset($similar_documents[$doc_id])){

                        $similar_documents[$doc_id]+=$score;

                    }
                    else{

                        $similar_documents[$doc_id]=$score;

                    }
                }
            }
        }

        // length normalise
        foreach($similar_documents as $doc_id => $score) {

            $similar_documents[$doc_id] = $score/$corpus['doc_count'][$doc_id];

        }

        // sort from  high to low

        arsort($similar_documents);

    }   

    return $similar_documents;
}

案例 1

$query = 'are';

$corpus = array(
    1 => 'How are you?',
);

$match_results=get_similar_documents($query,$corpus);
echo '<pre>';
    print_r($match_results);
echo '</pre>';

结果

Array
(
    [1] => 0.52832083357372
)

案例 2

$query = 'are';

$corpus = array(
    1 => 'how are you today?',
    2 => 'how do you do',
    3 => 'here you are! how are you? Are we done yet?'
);

$match_results=get_similar_documents($query,$corpus);
echo '<pre>';
    print_r($match_results);
echo '</pre>';

结果

Array
(
    [1] => 0.54248125036058
    [3] => 0.21699250014423
)

案例 3

$query = 'we are done';

$corpus = array(
    1 => 'how are you today?',
    2 => 'how do you do',
    3 => 'here you are! how are you? Are we done yet?'
);

$match_results=get_similar_documents($query,$corpus);
echo '<pre>';
    print_r($match_results);
echo '</pre>';

结果

Array
(
    [3] => 0.6813781191217
    [1] => 0.54248125036058
)

还有很多改进需要做 但是该模型提供了一种从自然查询中获得良好结果的方法, 没有布尔运算符,例如 、 或 。strpos()preg_match()strstr()stristr()

诺塔·贝恩

(可选)在搜索单词之前消除冗余

  • 从而减小索引大小并减少存储需求

  • 更少的磁盘 I/O

  • 更快的索引和更快的搜索。

1. 规范化

  • 将所有文本转换为小写

2. 停用词消除

  • 从文本中删除没有实际含义的单词(如“和”、“或”、“the”、“for”等)

3. 字典替换

  • 用具有相同或相似含义的其他词语替换词语。 (例如:将“饥饿”和“饥饿”替换为“饥饿”)

  • 可以执行进一步的算法措施(滚雪球)以进一步将单词简化为其基本含义。

  • 用十六进制等价物替换颜色名称

  • 通过降低精度来减少数值是规范化文本的其他方法。

资源

10赞 Shapeshifter #17

您需要使用相同/不相同的运算符,因为 strpos 可以返回 0 作为其索引值。如果您喜欢三元运算符,请考虑使用以下运算符(我承认似乎有点倒退):

echo FALSE === strpos($a,'are') ? 'false': 'true';
14赞 Pratik Joshi #18

您应该使用不区分大小写的格式,因此如果输入的值在 或 这无关紧要。smallcaps

<?php
$grass = "This is pratik joshi";
$needle = "pratik";
if (stripos($grass,$needle) !== false) { 

 /*If i EXCLUDE : !== false then if string is found at 0th location, 
   still it will say STRING NOT FOUND as it will return '0' and it      
   will goto else and will say NOT Found though it is found at 0th location.*/
    echo 'Contains word';
}else{
    echo "does NOT contain word";
}
?>

在这里,stripos 在不考虑大小写(小写/大写)的情况下在嘿嘿堆中找到针头。

带有输出的 PHPCode 示例

16赞 Somwang Souksavatd #19

简写版本

$result = false!==strpos($a, 'are');

评论

5赞 Bono 3/13/2015
虽然这个代码片段可能会解决这个问题,但包括一个解释确实有助于提高你的帖子的质量。请记住,您正在为将来的读者回答问题,而这些人可能不知道您的代码建议的原因。
14赞 Mathias Stavrou #20

也许你可以使用这样的东西:

<?php
    findWord('Test all OK');

    function findWord($text) {
        if (strstr($text, 'ok')) {
            echo 'Found a word';
        }
        else
        {
            echo 'Did not find a word';
        }
    }
?>
15赞 DJC #21

为了找到一个“单词”,而不是出现一系列实际上可能是另一个单词一部分的字母,以下将是一个很好的解决方案。

$string = 'How are you?';
$array = explode(" ", $string);

if (in_array('are', $array) ) {
    echo 'Found the word';
}

评论

5赞 Sunny 5/18/2015
如果是,它将失败$stringAre are, are?
30赞 Armfoot #22

令我印象深刻的是,这里没有一个使用和类似函数的答案提到多字节字符串函数(2015-05-08)。strposstrstr

基本上,如果您在查找包含某些语言(例如德语、法语、葡萄牙语、西班牙语等)的特定字符的单词时遇到困难(例如:äéôçºñ),您可能希望在函数前面加上 .因此,接受的答案将改用 mb_strposmb_stripos(用于不区分大小写的匹配):mb_

if (mb_strpos($a,'are') !== false) {
    echo 'true';
}

如果不能保证所有数据都是 100% 的 UTF-8,则可能需要使用这些函数。mb_

一篇很好的文章,可以理解为什么是 Joel Spolsky 的 The Absolute Minimum Every Software Developer Absolutely, Positive Must Know About Unicode and Characters Sets (No Excuses!)

12赞 Akshay Khale #23

strpos 函数工作正常,但如果你想检查段落中的单词,那么你可以使用 .case-insensitivestriposPHP

例如

$result = stripos("I love PHP, I love PHP too!", "php");
if ($result === false) {
    // Word does not exist
}
else {
    // Word exists
}

查找字符串中第一个不区分大小写的子字符串的位置。

如果字符串中不存在该单词,则它将返回 false,否则它将返回该单词的位置。

27赞 Arshid KV #24

您可以使用以下功能:strstr

$haystack = "I know programming";
$needle   = "know";
$flag = strstr($haystack, $needle);

if ($flag){

    echo "true";
}

在不使用内置函数的情况下:

$haystack  = "hello world";
$needle = "llo";

$i = $j = 0;

while (isset($needle[$i])) {
    while (isset($haystack[$j]) && ($needle[$i] != $haystack[$j])) {
        $j++;
        $i = 0;
    }
    if (!isset($haystack[$j])) {
        break;
    }
    $i++;
    $j++;

}
if (!isset($needle[$i])) {
    echo "YES";
}
else{
    echo "NO ";
}

评论

3赞 T30 3/21/2016
如果搜索第一个单词,则崩溃
9赞 mvw #25

检查字符串是否包含特定单词?

这意味着字符串必须解析为单词(请参阅下面的注释)。

执行此操作并指定分隔符的一种方法是使用 (doc):preg_split

<?php

function contains_word($str, $word) {
  // split string into words
  // separators are substrings of at least one non-word character
  $arr = preg_split('/\W+/', $str, NULL, PREG_SPLIT_NO_EMPTY);

  // now the words can be examined each
  foreach ($arr as $value) {
    if ($value === $word) {
      return true;
    }
  }
  return false;
}

function test($str, $word) {
  if (contains_word($str, $word)) {
    echo "string '" . $str . "' contains word '" . $word . "'\n";
  } else {
    echo "string '" . $str . "' does not contain word '" . $word . "'\n" ;
  }
}

$a = 'How are you?';

test($a, 'are');
test($a, 'ar');
test($a, 'hare');

?>

一次跑步给

$ php -f test.php                   
string 'How are you?' contains word 'are' 
string 'How are you?' does not contain word 'ar'
string 'How are you?' does not contain word 'hare'

注意:在这里,我们并不是指每个符号序列的单词。

单词的实际定义是PCRE正则表达式引擎,其中单词是仅由单词字符组成的子字符串,由非单词字符分隔。

“单词”字符是任何字母或数字或下划线字符, 也就是说,任何可以成为Perl“单词”一部分的字符。这 字母和数字的定义由PCRE的字符控制 表,如果发生特定于区域设置的匹配,则可能会有所不同 (..)

13赞 Julien #26

如果要检查字符串是否包含多个特定单词,可以执行以下操作:

$badWords = array("dette", "capitale", "rembourser", "ivoire", "mandat");

$string = "a string with the word ivoire";

$matchFound = preg_match_all("/\b(" . implode($badWords,"|") . ")\b/i", $string, $matches);

if ($matchFound) {
    echo "a bad word has been found";
}
else {
    echo "your string is okay";
}

例如,这对于在发送电子邮件时避免垃圾邮件很有用。

12赞 4 revs, 4 users 53%M Razwan #27

可以使用以下函数检查字符串:

function either_String_existor_not($str, $character) {
    return strpos($str, $character) !== false;
}

评论

1赞 afarazit 8/20/2016
可以简化为return strpos($str, $character) !== false
9赞 devpro #28

特定字符串的另一种解决方案:

$subject = 'How are you?';
$pattern = '/are/';
preg_match($pattern, $subject, $match);
if ($match[0] == 'are') {
    echo true;
}

您也可以使用函数。strpos()

19赞 Shashank Singh #29

它可以通过三种不同的方式完成:

 $a = 'How are you?';

1-斯特里斯特()

 if (strlen(stristr($a,"are"))>0) {
    echo "true"; // are Found
 } 

2-strpos()

 if (strpos($a, "are") !== false) {
   echo "true"; // are Found
 }

3-preg_match()

 if( preg_match("are",$a) === 1) {
   echo "true"; // are Found
 }

评论

0赞 Shapeshifter 12/28/2015
很好,但 preg_match 是有风险的,因为它可以返回 false 或 0。您应该在 #1 中测试 ===3
8赞 Kamaro #30

用:

$text = 'This is a test';
echo substr_count($text, 'is'); // 2

// So if you want to check if is exists in the text just put
// in a condition like this:
if (substr_count($text, 'is') > 0) {
    echo "is exists";
}
30赞 John Slegers #31

在 PHP 中,验证字符串是否包含某个子字符串的最佳方法是使用一个简单的辅助函数,如下所示:

function contains($haystack, $needle, $caseSensitive = false) {
    return $caseSensitive ?
            (strpos($haystack, $needle) === FALSE ? FALSE : TRUE):
            (stripos($haystack, $needle) === FALSE ? FALSE : TRUE);
}

解释:

  • strpos 查找字符串中区分大小写的子字符串首次出现的位置。
  • StripOS 查找字符串中不区分大小写的子字符串第一次出现的位置。
  • myFunction($haystack, $needle) === FALSE ? FALSE : TRUE确保始终返回布尔值,并修复子字符串索引为 0 时的意外行为。myFunction
  • $caseSensitive ? A : B选择 strposstripos 来执行工作,具体取决于 的值。$caseSensitive

输出:

var_dump(contains('bare','are'));            // Outputs: bool(true)
var_dump(contains('stare', 'are'));          // Outputs: bool(true)
var_dump(contains('stare', 'Are'));          // Outputs: bool(true)
var_dump(contains('stare', 'Are', true));    // Outputs: bool(false)
var_dump(contains('hair', 'are'));           // Outputs: bool(false)
var_dump(contains('aren\'t', 'are'));        // Outputs: bool(true)
var_dump(contains('Aren\'t', 'are'));        // Outputs: bool(true)
var_dump(contains('Aren\'t', 'are', true));  // Outputs: bool(false)
var_dump(contains('aren\'t', 'Are'));        // Outputs: bool(true)
var_dump(contains('aren\'t', 'Are', true));  // Outputs: bool(false)
var_dump(contains('broad', 'are'));          // Outputs: bool(false)
var_dump(contains('border', 'are'));         // Outputs: bool(false)
25赞 T30 #32

许多使用 substr_count 的答案会检查结果是否为 。但是由于该语句认为 0 与 false 相同,因此您可以避免该检查并直接编写:>0if

if (substr_count($a, 'are')) {

若要检查是否不存在,请添加运算符:!

if (!substr_count($a, 'are')) {

评论

0赞 Andrejs Gubars 3/10/2017
井。。。部分正确,在 PHP 中 0 == false 为 true,但 0 === false 为 false
6赞 Mindexperiment #33

用:

$a = 'How are you?';
if (mb_strpos($a, 'are')) {
    echo 'true';
}

它执行多字节安全的 strpos() 操作。

评论

1赞 simhumileco 2/7/2017
这不是一个好的答案。如果搜索字符串位于搜索字符串的开头,则函数返回零,这将演变为 false。mb_strpos(...)
6赞 ShirleyCC #34

一个更简单的选择:

return ( ! empty($a) && strpos($a, 'are'))? true : false;

评论

0赞 mickmackusa 4/9/2021
简单?当表达式返回布尔值时,永远不需要写入。? true : false;
8赞 user1134181 #35

您还可以使用内置函数 strchr() 和 strrchr() 以及多字节字符串 mb_strchr() 和 mb_strrchr()扩展。 这些函数返回部分字符串,如果未找到任何内容,则返回字符串。FALSE

  • strchr()- 查找字符串的第一个匹配项(是 strstr() 的别名)。
  • strrchr()- 查找字符串中最后一个出现的字符。

评论

1赞 pmiranda 10/8/2019
对我来说,这是最好的答案哈哈。
7赞 simhumileco #36

我认为一个好主意是使用:mb_stpos

$haystack = 'How are you?';
$needle = 'are';

if (mb_strpos($haystack, $needle) !== false) {

    echo 'true';
}

因为此解决方案区分大小写并且对所有 Unicode 字符都是安全的


但你也可以这样做(sauch 响应还没有):

if (count(explode($needle, $haystack)) > 1) {

    echo 'true';
}

此解决方案还区分大小写并且对 Unicode 字符是安全的

此外,您不在表达式中使用否定,这会增加代码的可读性


以下是使用函数的其他解决方案:

function isContainsStr($haystack, $needle) {

    return count(explode($needle, $haystack)) > 1;
}

if (isContainsStr($haystack, $needle)) {

    echo 'true';
}