Jump to content

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.

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.