• Performing searches on strings using strpos

    0
    scissors
    April 23rd, 2009PaulUncategorized

    There are occasions where you might want to search for a phrase within a string in PHP. Using the PHP function strpos we can do just this nice and easily.

    It could be that you want to check to see if something exists within a string, maybe as part of some validation or as a conditional action. PHP enables to do this very simply and this can come in handy in all sorts of situations.

    As an example, I want to see if the word “string” appears in a sentence.

    $sentence = ‘Using strpos we can find out if a string exists in another string’;

    if ( strpos($sentence, ’string’) ) {
       // yes it does
    } else {
       // no it doesn’t
    }

    Obviously you can populate the sentence variable with database content within a loop or similar during practical applications.

    Also quite handy in PHP 5 only is the stripos function, which works in exactly the same way, but is case insensitive. So as an example the following would still find a result, whereas when using strpos it does not:

    $sentence = ‘Using stripos we can find out if a String exists even though it has a capital letter in it’;

    if ( stripos($sentence, ’string’) ) {
       // yes it does
    } else {
       // no it doesn’t
    }

    • Share/Save/Bookmark
    • Share/Save/Bookmark




Leave a Reply

Clickcha - The One-click Captcha