[php] How to search in an array with preg_match?

How do I search in an array with preg_match?

Example:

<?php
if( preg_match( '/(my\n+string\n+)/i' , array( 'file' , 'my string  => name', 'this') , $match) )
{
    //Excelent!!
    $items[] = $match[1];
} else {
    //Ups! not found!
}
?>

This question is related to php regex arrays preg-match

The answer is


$items = array();
foreach ($haystacks as $haystack) {
    if (preg_match($pattern, $haystack, $matches)
        $items[] = $matches[1];
}

Use preg_grep

$array = preg_grep(
    '/(my\n+string\n+)/i',
    array( 'file' , 'my string  => name', 'this')
);

$haystack = array (
   'say hello',
   'hello stackoverflow',
   'hello world',
   'foo bar bas'
);

$matches  = preg_grep('/hello/i', $haystack);

print_r($matches);

Output

Array
(
    [1] => say hello
    [2] => hello stackoverflow
    [3] => hello world
)

You can use array_walk to apply your preg_match function to each element of the array.

http://us3.php.net/array_walk


Examples related to php

I am receiving warning in Facebook Application using PHP SDK Pass PDO prepared statement to variables Parse error: syntax error, unexpected [ Preg_match backtrack error Removing "http://" from a string How do I hide the PHP explode delimiter from submitted form results? Problems with installation of Google App Engine SDK for php in OS X Laravel 4 with Sentry 2 add user to a group on Registration php & mysql query not echoing in html with tags? How do I show a message in the foreach loop?

Examples related to regex

Why my regexp for hyphenated words doesn't work? grep's at sign caught as whitespace Preg_match backtrack error regex match any single character (one character only) re.sub erroring with "Expected string or bytes-like object" Only numbers. Input number in React Visual Studio Code Search and Replace with Regular Expressions Strip / trim all strings of a dataframe return string with first match Regex How to capture multiple repeated groups?

Examples related to arrays

PHP array value passes to next row Use NSInteger as array index How do I show a message in the foreach loop? Objects are not valid as a React child. If you meant to render a collection of children, use an array instead Iterating over arrays in Python 3 Best way to "push" into C# array Sort Array of object by object field in Angular 6 Checking for duplicate strings in JavaScript array what does numpy ndarray shape do? How to round a numpy array?

Examples related to preg-match

Preg_match backtrack error Regular expression containing one word or another How to search in an array with preg_match? PHP preg_match - only allow alphanumeric strings and - _ characters Delimiter must not be alphanumeric or backslash and preg_match PHP is_numeric or preg_match 0-9 validation Regex: Specify "space or start of string" and "space or end of string" PHP regular expressions: No ending delimiter '^' found in PHP - regex to allow letters and numbers only