match entire string PHP

They have: 53 posts

Joined: Oct 2005

Hi all!
What I want to ask might be rather silly, but I have come across it a couple of days now and don't seem to find any solution.
Consider the following variables :

$var1= "ps :Hello and welcome to greece";
$var2= "ps :Hello and";
$var3= "ps :It was nice to meeting you";

My problem is that, when I check $var2, it matches both $var1 and $var3, because , as you can see, $var3 has "ps" in it.
So, I was wondering if there is a way of matching ENTIRE $var2 and not just portions of it. In this way, it would match only $var1 and not $var3...

Greg K's picture

He has: 2,145 posts

Joined: Nov 2003

What are you currently using to compare the strings?

Try strpos() (see http://www.php.net/strpos for more details)

This worked for me:

<?php
$var1
= \"ps :Hello and welcome to greece\";
$var2= \"ps :Hello and\";
$var3= \"ps :It was nice to meeting you\";

if (strpos(
$var1,$var2)===false)
    echo \"Not Found in Var1 \n\";
else
    echo \"Was Found in Var1 \n\";
   
if (strpos(
$var3,$var2)===false)
    echo \"Not Found in Var3 \n\";
else
    echo \"Was Found in Var3 \n\";
   
?>

-Greg

CptAwesome's picture

He has: 370 posts

Joined: Dec 2004

Well, what are you using for matching? ereg? why not do:
if($str == $var1)

== is an exact match...
=== is an exact match and type match

They have: 140 posts

Joined: Apr 2006

Try the strcmp function. That's your best bet.

strcmp
(PHP 3, PHP 4, PHP 5)

strcmp -- Binary safe string comparison
Description
int strcmp ( string str1, string str2 )

Returns < 0 if str1 is less than str2; > 0 if str1 is greater than str2, and 0 if they are equal.

Note that this comparison is case sensitive.

Greg K's picture

He has: 2,145 posts

Joined: Nov 2003

CptAwesome, your suggestion would work if the strings were the same length, from the post, he wants $var2 (ps :Hello and) to match against $var1 (ps :Hello and welcome to greece)

A direct if ($var2 == $var1) would return false. he would have to do something like:

if ($var2 == substr($var1,0,strlen($var2)))

For the strcmp, I wasn't sure, so I did a test:

<?php
  
echo 'v1 vs v2 results in: ' . strcmp($var1,$var2).\"\n\";
   echo 'v3 vs v2 results in: ' . strcmp(
$var3,$var2).\"\n\";
   echo 'v2 vs v1 results in: ' . strcmp(
$var2,$var1).\"\n\";
   echo 'v2 vs v3 results in: ' . strcmp(
$var2,$var3).\"\n\";
?>

gave me this:

Quote: v1 vs v2 results in: 18
v3 vs v2 results in: 1
v2 vs v1 results in: -18
v2 vs v3 results in: -1

So looks like that won't work as both var1 and var3 give the same type fo results (either > 0 or < 0 depending on order give)

-Greg

Want to join the discussion? Create an account or log in if you already have one. Joining is fast, free and painless! We’ll even whisk you back here when you’ve finished.