1
   $array = array(
            array('foo_test1','demo_test1'),
            array('foo_test2','demo_test2'),
            array('blah_test1','exp_test1'),
            array('blah_test2','exp_test2'),
            array('foo_test3','demo_test3')
            )

How to get all subarray which contains foo substring with its value using php and regExp.

Expected Output:

$array = array(
        array('foo_test1','demo_test1'),
        array('foo_test2','demo_test2'),
        array('foo_test3','demo_test3')
        )

3 Answers 3

2

You should be able to do it with

preg_grep($pattern,$array)
Sign up to request clarification or add additional context in comments.

1 Comment

This is exactly the code you need. I also searched for this function, but thought it would be called "array_match" or stg like that. :)
0
$input  = array( /* your array */ );
$output = array();

foreach ( $input as $data ) {
  $len = length($data);
  for ( $i = 0; $i < $len; ++$i ) {
    if ( strpos($data[$i], 'foo') > -1 ) {
      $output[] = $data;
      break;
    }
  }
}

Comments

0
$array = array(
    array('foo_test1','demo_test1'),
    array('foo_test2','demo_test2'),
    array('blah_test1','exp_test1'),
    array('blah_test2','exp_test2'),
    array('foo_test3','demo_test3')
);

$search = 'foo';
$res = array();
foreach ($array as $arr) {
    foreach ($arr as $value) {
        if (preg_match('~'.preg_quote($search,'~').'~',$value)) {
        // if one of the values in that array
        // has the search word in it...
            $res[] = $arr; break;
            // push it into the $res and break
            // the inner foreach loop
        }
    }
}
print_r($res);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.