php-regexHow to use word boundary in PHP regex?
Word boundary is a special character used in regular expressions to match the beginning or end of a word. In PHP, it is represented by the \b
character.
Example code
$string = 'This is a test string';
if (preg_match('/\btest\b/', $string)) {
echo 'Matched!';
}
Output example
Matched!
Code explanation
$string = 'This is a test string';
: This is the string we are searching in./\btest\b/
: This is the regular expression. The\b
characters indicate that we are looking for the word "test" and not a substring of it.preg_match('/\btest\b/', $string)
: This is the function call topreg_match()
which searches for a match in the given string.echo 'Matched!';
: This is the code that is executed if a match is found.
Helpful links
More of Php Regex
- How to use PHP regex with zero or more occurrences?
- How to use PHP regex to get a YouTube video ID?
- How to match a double quote in PHP regex?
- How to get the first match when using regex in PHP?
- How to use PHP regex to match an exact string?
- How to use PHP regex to match UUID?
- How to use the "s" modifier in PHP regex?
- How to match a space using PHP regex?
- How to match a single quote in PHP regex?
- How to use PHP regex to match an XML tag?
See more codes...