I'm quite new to regular expressions. Could you help me to create a pattern, which matches whole words, containing specific part? For example, if I have a text string "Perform a regular expression match" and if I search for express, it shuld give me expression, if I search for form, it should give me Perform and so on. Got the idea?
Asked
Active
Viewed 5.3k times
2 Answers
48
preg_match('/\b(express\w+)\b/', $string, $matches); // matches expression
preg_match('/\b(\w*form\w*)\b/', $string, $matches); // matches perform,
// formation, unformatted
Where:
\b
is a word boundary\w+
is one or more "word" character*\w*
is zero or more "word" characters
See the manual on escape sequences for PCRE.
* Note: although not really a "word character", the underscore _
is also included int the character class \w
.

Linus Kleen
- 33,871
- 11
- 91
- 99
-
That is great. Just what i was looking for... +1 – OrPaz Mar 14 '12 at 13:50
-
\b Word boundary, nice... Why haven't I seen that until now? Useful. – Andrew Dec 17 '15 at 20:38
-
beware because "+" is considered as a word boundary in PHP regex ! – Nadir Oct 03 '18 at 09:56
-
@Nadir Care to elaborate? Within a regular expression `+` is _"one or more characters"_. Outside, really anything that's not `[a-z]` is considered a word boundary. But why should I beware? I don't get the context. – Linus Kleen Oct 04 '18 at 07:38
-
here are more details: I had this issue is with the following code: preg_match_all("/#(\\w+)/", "#a2+u2lis", $hashtags); - I needed to workaround the fact that \w considers "+" as a word boundary : you end up with 2 words while I just want "a2+u2lis" in the result (context: it is PHP 5.3) – Nadir Oct 05 '18 at 09:30
4
This matches 'Perform':
\b(\w*form\w*)\b
This matches 'expression':
\b(\w*express\w*)\b

Kyle Wild
- 8,845
- 2
- 36
- 36