Find text in string in PHP
This should be pretty straightforward, but I can't seem to find an explanation anywhere on how to do it.
I have a string in 开发者_如何学CPHP. That string might contain within it somewhere the substring ":ERROR:". I need to find if it has that string. strpos()
has worked perfectly up to this point, until today when ":ERROR:" was the first item in the string, so strpos()
returned 0
, so the program kept running thinking it had no error.
I don't need to replace the string, or do any manipulation to it, I just need a simple true/false
answer to "does :ERROR: exist in the string?"
strpos
returns false
when the string is not found, so check for false
instead of making an implicit condition.
if(strpos($string, ':ERROR:') !== false) {
// Do something...
}
As Anurag said in the comments, with functions like these it's always best to do a strict comparison (===
instead of just leaving out the operator or using ==
) because that's a common source of bugs, especially in PHP, where many functions can return values of different types.
The PHP Manual on strpos()
:
This function may return Boolean FALSE, but may also return a non-Boolean value which evaluates to FALSE, such as 0 or "". Please read the section on Booleans for more information. Use the === operator for testing the return value of this function.
if (strpos($myString, ":ERROR:") !== FALSE) {
// Error!
}
You can also avoid the strpos()
problems of not checking with a strict type operator by using the lesser known strstr()
if(strpos($string, ':ERROR:') !== false){
//found ':ERROR:' in string
}
"[strpos()] [r]eturns the position as an integer. If needle is not found, strpos() will return boolean FALSE."
http://php.net/manual/en/function.strpos.php
If the position is 0, then merely using == or != will evaluate 0 and false as equivalent. So use === or !== to avoid type coercion.
精彩评论