What I have now:
preg_match('/title:(. ?)(?=\s|$)/',$str, $result);
// Gives me words starts with title: and end with space.preg_match('/body:(. ?)(?=\s|$)/',$str, $result);
// Gives me words starts with body: and end with space.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:
- Remove string (I expect just one) that starts with
title:
and ends with a space. - Remove string (I expect just one) that starts with
body:
and ends with a space. - Remove strings (I expect multiple) that starts with
#
and ends with a space. - 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
), thentitle
orbody
, then:
and then one or more non-whitespace chars|
- or#\w
- a#
char and then one or more Unicode (due tou
flag) word chars
\s?
- an optional whitespace (change?
to*
if you need to match zero or more whitespaces).