Avatar of Rodrigo Costa
Rodrigo Costa
Flag for New Zealand asked on

Compare variable content to a string

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!
PHP

Avatar of undefined
Last Comment
Member_2_6009151

8/22/2022 - Mon
ASKER CERTIFIED SOLUTION
Member_2_6009151

Log in or sign up to see answer
Become an EE member today7-DAY FREE TRIAL
Members can start a 7-Day Free trial then enjoy unlimited access to the platform
Sign up - Free for 7 days
or
Learn why we charge membership fees
We get it - no one likes a content blocker. Take one extra minute and find out why we block content.
Not exactly the question you had in mind?
Sign up for an EE membership and get your own personalized solution. With an EE membership, you can ask unlimited troubleshooting, research, or opinion questions.
ask a question
Chris Stanyon

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
Member_2_6009151

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.
Chris Stanyon

Well spotted :)
Experts Exchange has (a) saved my job multiple times, (b) saved me hours, days, and even weeks of work, and often (c) makes me look like a superhero! This place is MAGIC!
Walt Forbes
Member_2_6009151

Caused myself a lot of issues with that in the past... you live and learn...