Domanda

I have a simple PHP array:

$array = array('Michael','Marian','Martina');

I have the following function to search for string starting with 'mi':

$array = preg_grep("/^Mi.*/", $array);

1) How to modify the regex to search for any part of the string not just the beginning of the string? For example searching ar would return Marian

2) How to make it case insensitive? For example searching for AR would also return Marian

I'm new to regex. Thanks

È stato utile?

Soluzione

Simple, you change your regex pattern and remove the ^ which specifies it has to be the start of the string. Case insensitivity can be achieved with the i modifier.

$matching_letters = 'ri';
$array = preg_grep("/{$matching_letters}/i", $array);

// Marian

Demo: https://eval.in/151916

Edit: you can also remove the .*(s) in this case and just match the letters.

For future reference, Regex101.com and PHPLiveRegex.com will do you wonders for learning regex.

Altri suggerimenti

1) Your regex matches the "start of string" anchor, ^. To match anywhere, simply remove the anchor.

2) Use the case insensitive modifier. These come after the final slash, and can be found here: http://www.php.net/manual/en/reference.pcre.pattern.modifiers.php. Example: $array = preg_grep("/^Mi.*/i", $array);

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top