0

I am trying to build a logic which will check a string for matching pattern. The pattern to match is build like this :

+ = and
/ = or

Example of pattern : "a+(b/c)" - which means that the string should contain "a" AND either a "b" or "c".

In this case the following strings should result in :

"ac" = true
"ab" = true
"abc" = true
"decfga" = true

"ad" = false
"bc" = false
"cb" = false

How would you do this in PHP? Is there a clever way to use preg_match for this task?

theduck
  • 2,526
  • 13
  • 15
  • 22
Martin
  • 393
  • 1
  • 3
  • 9
  • Comments are not for extended discussion; this conversation has been [moved to chat](https://chat.stackoverflow.com/rooms/205110/discussion-on-question-by-martin-check-if-string-matches-specific-pattern). – Cody Gray Dec 30 '19 at 21:32

1 Answers1

0

Thanks to you guys I managed to build a regex from the passed pattern syntax.

This is the code example I ended up with

$pattern = "e+(d/s)";
$string = "es";

$a = str_replace(array("(",")","/"),array("","",""),$pattern);
$b = explode("+",$a);
$ext = "";
for ($i=0; $i<@count($b); $i++) {
    @$c = $b[$i];
    if (strlen($c)>1) $c = "[".$c."]";
    @$ext .= "(?=.*".$c.")";
}
$ext = "/^".$ext.".+$/m";
$test = preg_match($ext,$string);
Martin
  • 393
  • 1
  • 3
  • 9