Home > Mobile >  How to write a regex pattern which matches following Array?
How to write a regex pattern which matches following Array?

Time:12-16

I want to write a regex pattern that user enters values matches the any one of the index in the following array ,can you please help me to achieve this thing...

$cars=['bmw','Audi','Ferari','BenZ',];
$regex_pattern=^[A-Za-z] (?: [A-Za-z] )*$;  //it takes the value only string with space or without space,now i want to match the pattern with the given array values .

if(preg_match($regex_pattern,$request->search)){
    my logic
}

InvalidScenarios:

Flight

Ship

Valid-Scenarios:

bmw

Audi

Ferari

Benz

CodePudding user response:

you can use

$matches = preg_grep ('/^ship (\w )/i', $cars); Output : []

$matches = preg_grep ('/^bmw (\w )/i', $cars); Output : [ 0 => 'bmw' ];

It will return array of values matched. You can check for $matches if it is an empty array that means you don't have any match.

Reference : https://www.php.net/manual/en/function.preg-grep.php

CodePudding user response:

$cars=['bmw','Audi','Ferari','BenZ',];
$regex_pattern=^[A-Za-z ] $;  //it takes the value only string with space or without space,now i want to match the pattern with the given array values .

if(preg_match($regex_pattern,$request->search)){
    my logic
}

CodePudding user response:

You could write a dynamic pattern to assert for the word in the string, and then use your regex to match only the allowed characters.

$cars=['bmw','Audi','Ferari','BenZ'];
$str = 'bmw
Audi
Ferari
Benz
Flight
Ship';
$regex_pattern = sprintf
("/^(?=.*\b(?:%s)\b)[A-Za-z] (?: [A-Za-z] )*$/im",
    implode('|', $cars)
);
preg_match_all($regex_pattern, $str, $matches);
var_dump($matches[0]);

Output

array(4) {
  [0]=>
  string(3) "bmw"
  [1]=>
  string(4) "Audi"
  [2]=>
  string(6) "Ferari"
  [3]=>
  string(4) "Benz"
}
  • Related