Jump to content

search an array with regex


tastro

Recommended Posts

hi,

 

also i need to make a new array which includes all regex matches or strstr matches (it doesn't need to be regex) from the old array.

 

now i have it like this:

 

$array=array('cathouse','doghouse','mousehouse');
preg_match_all("@\,([a-zA-Z0-9\|]+dog[a-zA-Z0-9\|]+)\,@i",',|'.implode("|,|",$array).'|,',$matches);
print_r($matches[1]);

 

but is there a faster way to do this? (i tryed with loops but it's all slower)

 

i also have all this in another loop. because it must match more words/strings then only "dog".

 

EDITED.

Link to comment
https://forums.phpfreaks.com/topic/247518-search-an-array-with-regex/
Share on other sites

<?php 

$array = array('cathouse','doghouse','mousehouse','snoopdog');
$search = 'dog';

// Here's how you can do with with array_walk and an anonymous function
$resultWalk = array();
array_walk( $array,
create_function( '$value,$key,$data',
	'if( strstr($value,$data[1])!==FALSE ) $data[0][] = $value;'
),
array(&$resultWalk,$search)
);

print_r( $resultWalk );

// Here's how you can do it using a simple foreach
$resultLoop = array();
foreach( $array as $value ) {
if( stristr($value,$search) !== FALSE ) $resultLoop[] = $value;
}

print_r( $resultLoop );

?>

Not sure exactly, but this should work.  You can build the cat|dog|mouse dynamically beforehand, no need for loops:

 

$array = array('cathouse','doghouse','mousehouse');
$matches = preg_grep("@[\w\d]*cat|dog|mouse[\w\d]*@i", $array);
print_r($matches);

i also have all this in another loop. because it must match more words/strings then only "dog".

 

If you state your overall goal with an example showing what you are starting with and what the end result should be, it will often lead to the best solution. I can easily imagine you can do whatever it is you are actually trying to accomplish inside one query or using one preg_ statement.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.