Chead Chead - 1 month ago 12
PHP Question

PHP - How to check if a string contain any text

<?php
$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
Answer

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.