0

I want to match some words in regex except some others:

ex: all words that contains straat, laan, baan

(straat|laan|baan)

But not

(overslaan|bestraat|rubaan)

ex: mystraat bolaan overslaan boobaan rubaan

should match

mystraat bolaan boobaan

Casimir et Hippolyte
  • 88,009
  • 5
  • 94
  • 125
yarek
  • 11,278
  • 30
  • 120
  • 219
  • 1
    This has been answered a number of times. You can use look-ahead assertions. See http://stackoverflow.com/questions/611883/regex-how-to-match-everything-except-a-particular-pattern – fjc Jan 22 '17 at 13:03
  • 2
    If you want to match whole words, not just parts, something like this should work: https://regex101.com/r/LLE1XQ/2 – sinisake Jan 22 '17 at 13:39

2 Answers2

1

That's a bit complex but can be done with a negative lookbehind.

Try something like this:

$goodString = "coolbaan";
$badString = "rubaan";

$stringToTest = $goodString;

$regexPattern = '/(.*?)((?<!overs|ru|be)(straat|laan|baan))/';

preg_match($regexPattern, $stringToTest, $matches);
if ($matches) {
  // $matches[1] will be the prefix - e.g. ru
  // $matches[2] will be the suffix e.g. baan
  // $result will be 'rubaan'
  $result = "{$matches[1]}{$matches[2]}";
} else {
  $result = 'No Match!';
}
echo $result;
Z-Bone
  • 1,534
  • 1
  • 10
  • 14
-2

just add ^ in front of your regex and $ to end check below code:

/^[straat|laan|baan]$/