PHP Regex Word Boundary (\b) (original) (raw)

Skip to content

Summary: in this tutorial, you’ll learn to use the regex word boundary to match the word boundary position in a string.

Introduction to the regex word boundary #

The word boundary anchor \b matches a position called a word boundary in a string.

A word boundary’s position can be one of the following:

The following picture illustrates the word boundary positions in the string "PHP IS COOL!":

In other words, the word boundary allows you to match the whole word using the regular expression:

/\bword\b/Code language: PHP (php)

The following example matches PHP in the string:

`<?php

$pattern = '/PHP/'; $title = 'PHP is awesome. How is CakePHP?';

if (preg_match_all($pattern, title,title, title,matches)) { print_r($matches[0]); }`Code language: PHP (php)

Try it

Output:

Array ( [0] => PHP [1] => PHP )Code language: PHP (php)

It returns the first match as PHP and the second as PHP in the CakePHP. However, if you add the word boundary (\b) to the regular expression, it matches only the word PHP:

`<?php

$pattern = '/\bPHP\b/'; $title = 'PHP is awesome. How is CakePHP?';

if (preg_match_all($pattern, title,title, title,matches)) { print_r($matches[0]); }`Code language: PHP (php)

Try it

Output:

Array ( [0] => PHP )Code language: PHP (php)

Summary #

Did you find this tutorial useful?