Chead Chead - 7 days ago 4x
PHP Question

PHP - How to check if a string contain any text

$a = '';

if($a exist 'some text')
echo 'text';

Suppose I have the code above, how to write the statement "if($a exist 'some text')"?

Dai Dai

Use strpos

$haystack = "foo bar baz";
$needle   = "bar"

if( strpos( $haystack, $needle ) !== false ) {
    echo "\"bar\" exists in the haystack variable";

In your case:

if( strpos( $a, 'some text' ) !== false ) echo 'text';

Note that my use of the !== operator (instead of != false or == true or even just if( strpos( ... ) ) {) is because of the "truthy"/"falsy" nature of PHP's handling of the return value of strpos.