Page 1 of 1

Regular Expressions

Posted: Sun May 06, 2007 7:24 pm
by xterra
Hello,
I have one string like this: 1,2,3,4,5

And another that may contain one, or more of those numbers, like this: 2,4. Or possibly, 1,3,5, etc.

I just need to make sure the second group has at least one number in common with the first.

Can anyone assist?

Thank you

Posted: Sun May 06, 2007 7:55 pm
by Begby
You can do this using explode() and then comparing the resulting arrays. Check it out on php.net.

Posted: Sun May 06, 2007 8:17 pm
by xterra
Begby wrote:You can do this using explode() and then comparing the resulting arrays. Check it out on php.net.
Been there. Wouldn't split() be better?

This is what I have:

Code: Select all

$splitArray=split(",",$require);
But I don't know how to get the size of that array. sizeof does not work.

Posted: Sun May 06, 2007 8:33 pm
by DrTom
In this case, using explode is far more effecient than split being as how split has the overhead of using a regex engine and explode does not.

Also, you can use array_intersect on the exploded arrays to get the elements that are in both. Something like this

Code: Select all

$str1 = '1,2,3,4,5,6,7,8';
 $str2 = '3,4,5,9';

 $arr1 = explode(',',$str1);
 $arr2 = explode(',',$str2);

 //get an array containing the common elements
 $res = array_intersect($arr1,$arr2);

 if(count($res))
 {
   echo "Hooray I have atleast one in str2 that is in str1\n"; 
 }
 else
 {
   echo "Boo. Nothing in str2 was in str1\n";
 }