Match whole word from partial-word search string
Asked Answered
R

2

27

Could you help me to create a pattern, which matches whole words, containing a specific part? For example, if I have a text string Perform a regular expression match and if I search for express, it should give me expression, if I search for form, it should give me Perform and so on.

Reactionary answered 18/1, 2011 at 8:41 Comment(0)
D
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.

Discontinuation answered 18/1, 2011 at 8:44 Comment(0)
D
4

This matches 'Perform':

\b(\w*form\w*)\b

This matches 'expression':

\b(\w*express\w*)\b
Dacca answered 18/1, 2011 at 8:51 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.