Regular Expressions

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
xterra
Forum Commoner
Posts: 69
Joined: Mon Mar 06, 2006 12:52 pm

Regular Expressions

Post 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
Begby
Forum Regular
Posts: 575
Joined: Wed Dec 13, 2006 10:28 am

Post by Begby »

You can do this using explode() and then comparing the resulting arrays. Check it out on php.net.
xterra
Forum Commoner
Posts: 69
Joined: Mon Mar 06, 2006 12:52 pm

Post 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.
DrTom
Forum Commoner
Posts: 60
Joined: Wed Aug 02, 2006 8:40 am
Location: Las Vegas

Post 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";
 }
Post Reply