Search code examples
phpstrpos

How to check if a fixed string contain any additional character?


This code check if "have" is present inside the string, assuming the string always begin with "I have found" what i need is a function that check if the string contain "I have found" plus something else. Example: I have found 500. where 500 can be anything, and unknow.

 $a = 'I have found';
 if (strpos($a, 'have') !== false) {
 echo 'true';
 }

Solution

  • If you want to know what has been found:

    function get_found($str){
        if(strpos($str, "I have found")===false)
            return "nothing";
        $found = trim(substr($str, strlen("I have found")));
        if($found == "")
            return "nothing";
        return $found;
    }
    
    echo get_found("I have found a friend"); //outputs "a friend"
    echo get_found("I have found"); //outputs "nothing"