regex with an array

Any questions involving matching text strings to patterns - the pattern is called a "regular expression."

Moderator: General Moderators

Post Reply
rubberjohn
Forum Contributor
Posts: 193
Joined: Fri Feb 25, 2005 4:03 am

regex with an array

Post 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
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post by feyd »

I'd avoid regex in this instance. Instead, I'd explode the tested string then use in_array()
rubberjohn
Forum Contributor
Posts: 193
Joined: Fri Feb 25, 2005 4:03 am

Post 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
rubberjohn
Forum Contributor
Posts: 193
Joined: Fri Feb 25, 2005 4:03 am

Post 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
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post 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.
rubberjohn
Forum Contributor
Posts: 193
Joined: Fri Feb 25, 2005 4:03 am

Post by rubberjohn »

ok cheers feyd i'll try that instead
Post Reply