Search code examples
phpstrpos

search tags in a php string with strpos


this is an UTF-8 string

$string = '<h2> a none english char - utf-8 string </h2>';

I want to check <h2> tag exist in $string or not

I try:

if(strpos($string , '<h2>'))
or
if(strpos($string , '<h2>') == true )
or
if(strpos($string , '<h2>') === true)
or
if(mb_strpos($string , '<h2>' ))

but all of these condition retrun false. whats the wrong?


Solution

  • Your tests fail because your "needle" string occurs right at the start of your haystack, therefore strpos() will return 0, to indicate start-of-string.

    if (0)          -> false
    if (0 == true)  -> false
    if (0 === true) -> false
    

    You cannot use equality in this case, you must use inequality:

    if (strpos(...) !== FALSE)
    

    comment followup:

    I fail to see how it could "no effect at all":

    php > $string = '<h2> a none english char - utf-8 string </h2>';
    php > var_dump(strpos($string, '<h2>'));
    int(0)
    php > var_dump(strpos($string, '<h2>') == true);
    bool(false)
    php > var_dump(strpos($string, '<h2>') === true);
    bool(false)
    php > var_dump(mb_strpos($string, '<h2>'));
    int(0)
    php > var_dump(mb_strpos($string, '<h2>') !== false);
    bool(true)