How do I check if a string contains a specific wor

2018-12-31 01:12发布

Consider:

$a = 'How are you?';

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

Suppose I have the code above, what is the correct way to write the statement if ($a contains 'are')?

30条回答
只靠听说
2楼-- · 2018-12-31 01:21

Using strstr() or stristr() if your search should be case insensitive would be another option.

查看更多
余欢
3楼-- · 2018-12-31 01:23

I had some trouble with this, and finally I chose to create my own solution. Without using regular expression engine:

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;
 }

You may notice that the previous solutions are not an answer for the word being used as a prefix for another. In order to use your example:

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

With the samples above, both $a and $b contains $c, but you may want your function to tell you that only $a contains $c.

查看更多
几人难应
4楼-- · 2018-12-31 01:23

Another option to finding the occurrence of a word from a string using strstr() and stristr() is like the following:

<?php
    $a = 'How are you?';
    if (strstr($a,'are'))  // Case sensitive
        echo 'true';
    if (stristr($a,'are'))  // Case insensitive
        echo 'true';
?>
查看更多
荒废的爱情
5楼-- · 2018-12-31 01:23

You need to use identical/not identical operators because strpos can return 0 as it's index value. If you like ternary operators, consider using the following (seems a little backwards I'll admit):

echo FALSE === strpos($a,'are') ? 'false': 'true';
查看更多
柔情千种
6楼-- · 2018-12-31 01:24

Do not use preg_match() if you only want to check if one string is contained in another string. Use strpos() or strstr() instead as they will be faster. (http://in2.php.net/preg_match)

if (strpos($text, 'string_name') !== false){
   echo 'get the string';
}
查看更多
后来的你喜欢了谁
7楼-- · 2018-12-31 01:25

You should use case Insensitive format,so if the entered value is in small or caps it wont matter.

<?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";
}
?>

Here stripos finds needle in heystack without considering case (small/caps).

PHPCode Sample with output

查看更多
登录 后发表回答