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:43

The short-hand version

$result = false!==strpos($a, 'are');
查看更多
只靠听说
3楼-- · 2018-12-31 01:44

Another option is to use the strstr() function. Something like:

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

Point to note: The strstr() function is case-sensitive. For a case-insensitive search, use the stristr() function.

查看更多
浪荡孟婆
4楼-- · 2018-12-31 01:44

A string can be checked with the below function:

function either_String_existor_not($str, $character) {
    if (strpos($str, $character) !== false) {
        return true;
    }
    return false;
}
查看更多
春风洒进眼中
5楼-- · 2018-12-31 01:45

To determine whether a string contains another string you can use the PHP function 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";
}

?>

CAUTION:

If the needle you are searching for is at the beginning of the haystack it will return position 0, if you do a == compare that will not work, you will need to do a ===

A == sign is a comparison and tests whether the variable / expression / constant to the left has the same value as the variable / expression / constant to the right.

A === sign is a comparison to see whether two variables / expresions / constants are equal AND have the same type - i.e. both are strings or both are integers.

查看更多
高级女魔头
6楼-- · 2018-12-31 01:47

If you want to avoid the "falsey" and "truthy" problem, you can use substr_count:

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

It's a bit slower than strpos but it avoids the comparison problems.

查看更多
旧人旧事旧时光
7楼-- · 2018-12-31 01:48

It can be done in three different ways:

 $a = 'How are you?';

1- stristr()

 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
 }
查看更多
登录 后发表回答