Search code examples
phpstrpos

PHP strpos to match querystring text pattern


I need to execute a bit of script only if the $_GET['page'] parameter has the text "mytext-"

Querystring is: admin.php?page=mytext-option

This is returning 0:

$myPage = $_GET['page'];
$match = strpos($myPage, 'mytext-');
echo $match;

Solution

  • strpos returns the position of the string. Since it's 0, that means it was found at position 0, meaning, at the start of the string.

    To make an easy way to understand if it's there, add the boolean === to an if statement like this:

    <?php
    
    $myPage = $_GET['page'];
    $match = strpos($myPage, 'mytext-');
    
    if ( $match === false ) {
        echo 'Not found';
    } else {
        echo 'Found';
    }
    
    ?>
    

    This will let you know, if the string is present or not.

    Or, if you just need to know, if it's there:

    $myPage = $_GET['page'];
    $match = strpos($myPage, 'mytext-');
    
    if ( $match !== false ) {
        echo 'Found';
    }
    
    ?>