James P. Wright
James P. Wright

Reputation: 9131

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

Upvotes: 1

Views: 8358

Answers (4)

Mike B
Mike B

Reputation: 32145

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

Upvotes: 2

alex
alex

Reputation: 490143

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

Upvotes: 1

Sasha Chedygov
Sasha Chedygov

Reputation: 130777

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.

Upvotes: 3

micahwittman
micahwittman

Reputation: 12476

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.

Upvotes: 0

Related Questions