开发者

php - how to test if a string contains an uppercase word?

$string = "ttest test NEEDLE haystack";

How do I match to see if the $string contains the uppercase wor开发者_C百科d "NEEDLE"?

I have been using if ( stristr($string, 'NEEDLE') === TRUE ) but it is not case sensitive.

TIA


Just use strstr instead

if ( strstr($string, 'NEEDLE') === TRUE )

However: this will still fail, because the strstr function and stristr return a string and only a boolean, if the sub-string is not found. You could also use strpos instead, which returns either an integer or false, if the substring was not found:

if (strpos($string, 'NEEDLE') !== false)


You can use the function strstr, which is the case-sensitive version of stristr:

if ( strstr($string, 'NEEDLE') !== false ) {
  // do something...
}

Note that strstr documentation recommends using strpos if you just only want to know if the needle occurs within the haystack.

If you need more complex comparisons you could also use preg_match, but in this case I think strstr is enough.


Use the case-sensitive strpos:

if (strpos($string, 'NEEDLE') !== false)

strstr would work as well here, but unnecessarily returns the rest of the string instead of just a short indication where it has been matched. Note that neither of stristr, strstr, or strpos ever return true.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜