1

I have a PHP array with a parent called "items." In that array, I want to remove all values that do not contain a string (which I'm gonna use regex to find). How would I do this?

1
  • if you're just looking to match against a string, consider using strpos instead of a RegEx - faster, especially if the Array is large. Commented Apr 26, 2012 at 17:22

2 Answers 2

4
foreach($array['items'] as $key=>$value) { // loop through the array
    if( !preg_match("/your_regex/", $value) ) {
        unset($array['items'][$key]);
    }
}
Sign up to request clarification or add additional context in comments.

Comments

2

You can try using array_filter.

$items = array(
    #some values
);
$regex= '/^[some]+(regex)*$/i';
$items = array_filter($items, function($a) use ($regex){
    return preg_match($regex, $a) !== 0;
});

NOTE: This only works in PHP 5.3+. In 5.2, you can do it this way:

function checkStr($a){
    $regex= '/^[some]+(regex)*$/i';
    return preg_match($regex, $a) !== 0;
}

$items = array(
    #some values
);
$items = array_filter($items, 'checkStr');

1 Comment

I prefer this approach to brute force looping over the array, good answer.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.