Home > OS >  PHP Regex - Exclude 3 conditions and return the rest
PHP Regex - Exclude 3 conditions and return the rest

Time:11-10

What I have now:

  1. preg_match('/title:(. ?)(?=\s|$)/',$str, $result); // Gives me words starts with title: and end with space.
  2. preg_match('/body:(. ?)(?=\s|$)/',$str, $result); // Gives me words starts with body: and end with space.
  3. preg_match_all('/#([\p{Pc}\p{N}\p{L}\p{Mn}] )/u', $str, $result); // Gives me array of words starts with # and put them into an array.

How to exclude the above and get the rest that doesn't match in one expression?

I want to take the user input, and:

  1. Remove string (I expect just one) that starts with title: and ends with a space.
  2. Remove string (I expect just one) that starts with body: and ends with a space.
  3. Remove strings (I expect multiple) that starts with # and ends with a space.
  4. Get whatever words are left.

Ex: title:hello mexico body:something #css#php #html city

Result should be: mexico city

CodePudding user response:

You can use

$str = preg_replace('~(?:\b(?:title|body):\S |#\w )\s?~u', "", $str);

See the PHP demo and the regex demo.

Details:

  • (?:\b(?:title|body):\S |#\w ) - either of
    • \b(?:title|body):\S - a word boundary (\b), then title or body, then : and then one or more non-whitespace chars
    • | - or
    • #\w - a # char and then one or more Unicode (due to u flag) word chars
  • \s? - an optional whitespace (change ? to * if you need to match zero or more whitespaces).
  • Related