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\bcharacters 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 to match a zip code?
- How to match a quotation mark in PHP regex?
- How to use PHP regex to match a year?
- How to use PHP regex with zero or more occurrences?
- How to use PHP regex to match an exact string?
- How to use PHP regex to match a nbsp HTML whitespace?
- How to use PHP regex to get a YouTube video ID?
- How to use PHP regex to match special characters?
- How to use PHP regex to match whitespace?
- How to use PHP regex to match UUID?
See more codes...