tags:

views:

71

answers:

4

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 PHP. 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?"

+3  A: 

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!
}
Mike B
A: 
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.

micahwittman
+2  A: 

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.

musicfreak
+1  A: 

You can also avoid the strpos() problems of not checking with a strict type operator by using the lesser known strstr()

alex