PHP string search

Question

Answers ( 1 )

    0
    2024-01-11T18:05:24+00:00
    1. strpos():

      • Use: To find the position of the first occurrence of a substring in a string.
      • Returns: The position of the first occurrence of the substring, or false if the substring is not found.
      • Example:
        $myString = "Hello, world!";
        $findMe   = "world";
        $pos = strpos($myString, $findMe);
        
        if ($pos === false) {
            echo "The string '$findMe' was not found in the string '$myString'";
        } else {
            echo "The string '$findMe' was found in the string '$myString'";
            echo " and exists at position $pos";
        }
        
    2. strstr() / stristr():

      • Use: To find the first occurrence of a substring in a string. stristr() is case-insensitive.
      • Returns: The part of the string starting from and including the first occurrence of the substring, or false if the substring is not found.
      • Example:
        $email  = 'user@example.com';
        $domain = strstr($email, '@');
        echo $domain; // prints @example.com
        
    3. strrpos():

      • Use: To find the position of the last occurrence of a substring in a string.
      • Returns: The position of the last occurrence of the substring, or false if the substring is not found.
      • Example:
        $myString = "abc abc";
        $findMe   = "abc";
        $pos = strrpos($myString, $findMe);
        echo $pos; // prints 4
        
    4. preg_match() / preg_match_all():

      • Use: For regular expression pattern matching. preg_match_all() finds all matches.
      • Returns: preg_match() returns 1 if the pattern matches given subject, 0 if it does not, or false if an error occurred. preg_match_all() returns the number of full pattern matches.
      • Example:
        $string = "The rain in SPAIN falls mainly on the plains.";
        preg_match("/ain/i", $string, $matches);
        print_r($matches); // prints Array ( [0] => ain )
        
    5. strpos() with substr():

      • Combination: Sometimes you may need to use strpos() in combination with substr() to extract specific parts of a string based on a search.
      • Example:
        $myString = "Hello, world!";
        $findMe   = "world";
        $pos = strpos($myString, $findMe);
        
        if ($pos !== false) {
            $extracted = substr($myString, $pos, strlen($findMe));
            echo $extracted; // prints 'world'
        }
        

    Each of these functions has its own use case, and the choice of which to use depends on the specific requirements of the string search you are performing.

Leave an answer