STRINGS

Search String using strpos Example

This code Search String using strpos and strrpos Example

strpos() method is a good way to search string inside a string.

About the Code:

  • Search String using strpos Example
  • This code will search for string in a given string
  • Execute this code in console using > php <filename>
  • We will use strpos() and stripos() method to search the string
  • We will use strrpos() and strripos() method to search the string
  • strpos() – Find the position of the first occurrence of a substring in a string
  • strrpos() –  Find the position of the last occurrence of a substring in a string
  • PHP_EOL is used to print new line on the console


    $description = "This is a example of strpos method to search string using strpos.";
    $pos = strpos($description, "strpos");

    //$pos is false when the string is not found.
    //$pos === 0 means string is found at position 0.
    //Always check for false condition not 0.
    if( $pos === false ){
        echo "Confirmed! The String is not found" . PHP_EOL;
    }else{
        echo "String is found at Position: $pos" . PHP_EOL;
    }

    //Case in-sensitive search
    $pos = stripos($description, "STRPOS");

    //stripos - i indicates case-insensitive.
    if( $pos === false ){
        echo "Confirmed! The String is not found" . PHP_EOL;
    }else{
        echo "String is found at Position: $pos" . PHP_EOL;
    }

    //strrpos() - Find the position of the LAST occurrence of a substring in a string
    $pos = strrpos($description, "strpos");

    //strrpos() - search the last position
    if( $pos === false ){
        echo "Confirmed! The String is not found" . PHP_EOL;
    }else{
        echo "String is found at Position: $pos" . PHP_EOL;
    }

    //strripos() - Find the position of the LAST occurrence of a substring in a string
    $pos = strripos($description, "STRPOS");

    //strripos() - search the last position
    if( $pos === false ){
        echo "Confirmed! The String is not found" . PHP_EOL;
    }else{
        echo "String is found at Position: $pos" . PHP_EOL;
    }
    

Output:


String is found at Position: 21
String is found at Position: 21
String is found at Position: 58
String is found at Position: 58

About the author

PHPTraining.com

Do you know we teach Free PHP Course which has tons of Exercise, Assignments, Code Editor, Quiz and Certification. Access the course from here.

If you liked this article, then please subscribe to our YouTube Channel for PHP video tutorials. You can also find us on Twitter and Facebook.

Add Comment

Click here to post a comment