Link to home
Start Free TrialLog in
Avatar of Rodrigo Costa
Rodrigo CostaFlag 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!
Avatar of Member_2_6009151
Flag of United Kingdom of Great Britain and Northern Ireland image

Link to home
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of Chris Stanyon
Try using the strrpos() function.

$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 -
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.
Well spotted :)
Caused myself a lot of issues with that in the past... you live and learn...