Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP strpos to match querystring text pattern

Tags:

php

strpos

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;
like image 563
RegEdit Avatar asked Jan 26 '26 14:01

RegEdit


2 Answers

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';
}

?>
like image 85
Peon Avatar answered Jan 29 '26 03:01

Peon


Use substr() once you get the location of 'mytext-', like so:

$match = substr($myPage, strpos( $myPage, 'mytext-') + strlen( 'mytext-'));

Otherwise, strpos() will just return the numerical index of where 'mytext-' starts in the string.

You can also use str_replace() to accomplish this if your string only has 'mytext-' once:

$match = str_replace( 'mytext-', '', $myPage);
like image 23
nickb Avatar answered Jan 29 '26 03:01

nickb