Home > Backend Development > PHP Tutorial > How Can I Replace Whole Words Only Using Regex in PHP?

How Can I Replace Whole Words Only Using Regex in PHP?

Barbara Streisand
Release: 2024-12-07 18:22:13
Original
155 people have browsed it

How Can I Replace Whole Words Only Using Regex in PHP?

Regex-Based Word Replacement in PHP Strings

Replacing specific words within a string can be tricky if you want to ensure that only entire words are matched. In this particular case, the string text contains the word "Hello" in various forms, but we want to replace only complete occurrences of "Hello."

To achieve this, we can utilize PHP's regular expression functions. Regular expressions provide a powerful tool for matching patterns within strings. The key to limiting the replacement to whole words is the b metacharacter, which matches a word boundary.

By modifying the str_replace function to incorporate a regular expression, we can accomplish our goal:

$text = "Hello hellol hello, Helloz";
$newtext = preg_replace('/\bHello\b/', 'NEW', $text);
Copy after login

The b in the regular expression ensures that only entire occurrences of "Hello" are matched, excluding any partial or overlapped matches. The result will be:

NEW hellol hello, Helloz
Copy after login

This correctly replaces only the complete instances of "Hello" with "NEW" while leaving other variations untouched.

UTF-8 Unicode Handling:

If the text contains UTF-8 characters, an additional step is necessary to ensure proper recognition of word boundaries. UTF-8 encoding for Unicode characters requires the use of the "u" modifier in the regular expression:

$text = "Hello hellol こんにちは, Helloz";
$newtext = preg_replace('/\bHello\b/u', 'NEW', $text);
Copy after login

This will correctly replace all complete occurrences of "Hello" regardless of language or character encoding.

The above is the detailed content of How Can I Replace Whole Words Only Using Regex in PHP?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template