Compare variable content to a string

Rodrigo Costa
Rodrigo Costa used Ask the Experts™
on
Hi folks, I tried using javascript but it made it too convoluted, so here we go:

I need to retrieve a variable from a form in php that is named $url, I must compare this variable to the text "Tr123", and if this text is anywhere within the variable I need to echo "ok", else I need it to echo "no". I'm having a problem on finding out how to check for the content with only php...

Any help would be much appreciated, Cheers!
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
if(strpos($url, "Tr123") === false)
{
    echo "no";
}
else
{
    echo "ok";
}
Most Valuable Expert 2018
Distinguished Expert 2018

Commented:
Try using the strrpos() function.

<?php
$myVar = "Tr123";
$formVariable = $_POST['url'];

if (strrpos($formVariable, $myVar)) {
     echo "OK";
} else { 
     echo "No";
}
?>

Open in new window

Here's the manual page for it - http://php.net/manual/en/function.strrpos.php
chrisStanyon, your solution will not work in the case that the string starts with Tr123. strpos would return 0 which would resolve to false, meaning "No" would be printed despite the fact that it is in the string.

It may not be an issue here, but just thought it was worth a mention.
Most Valuable Expert 2018
Distinguished Expert 2018

Commented:
Well spotted :)
Caused myself a lot of issues with that in the past... you live and learn...

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial