Page 1 of 1

regex with an array

Posted: Fri Apr 14, 2006 1:25 pm
by rubberjohn
just started looking at regex - pretty complicated to get your head around but i get the idea (i think)


i have the following code that matches a variable with a string

Code: Select all

$search_data = array("2","4","51");

foreach($search_data as $value){

$pattern = "/\"".$value."\"/";
$do = preg_match_all($pattern, $post2, $matches);

	if($do){
		foreach($matches[0] as $value){
			$arr_matches[] = $value;
			
		}
	}else{
	
		$arr_matches[] = "00";
	
	}
}
so this will cycle through the search_data array and see if there is a match, if there is no match "00" is inserted so i can test for it later.

i know it is possible to specify the order that items must match but how can i achieve this with the method i am using above? or is there a better way of doing this? Because i need to make sure that the values don't just match but match in the same order as they occur in search_data. NB when i say same order i mean that other values can come in between

for example if search_data = 1,2 and 3 and was compared with the following strings...

STRING1 - 1,2,3

would be just as good as

STRING2 - 1,5,2,8,9,3

is that possible in one statement or would i need multiple preg_match statements

cheers for your help

rj

Posted: Fri Apr 14, 2006 1:40 pm
by feyd
I'd avoid regex in this instance. Instead, I'd explode the tested string then use in_array()

Posted: Fri Apr 14, 2006 1:58 pm
by rubberjohn
but the test 'subject' $post2 is an array previously generated by a set of linked lists and stored in a db

my other link provides the whole picture - viewtopic.php?t=47046

i was under the impression that imploding an array into a string to store in a db and then exploding the string when fetching should be avoided?

rj

Posted: Fri Apr 14, 2006 2:09 pm
by rubberjohn
i suppose i could just unserialize back into an array and do it that way

but then again - using in_array() will only test for their presence and not their order.

just so i know why would you not use regex in this case?

thanks

rj

Posted: Fri Apr 14, 2006 2:22 pm
by feyd
it's a simple search, starting the regex engine is overkill and you'll still have to incorporate a lot of added logic.

Posted: Fri Apr 14, 2006 2:45 pm
by rubberjohn
ok cheers feyd i'll try that instead