Home > Backend Development > PHP Tutorial > How Can I Replace Whole Words in a String Using Regular Expressions?

How Can I Replace Whole Words in a String Using Regular Expressions?

Patricia Arquette
Release: 2024-12-09 00:59:10
Original
871 people have browsed it

How Can I Replace Whole Words in a String Using Regular Expressions?

Finding and Replacing Whole Word Matches in a String

When working with strings, it's common to need to replace specific words or phrases. However, simply using a string replacement function like str_replace() can lead to unexpected results, as it replaces all occurrences of the pattern regardless of its position within a word.

To address this, regular expressions can be employed to match only whole word instances of a pattern. The key to this is the word boundary metacharacter, denoted by "b".

Using Regular Expressions

To replace only whole word matches, use the following regular expression pattern:

/\bHello\b/
Copy after login

Here's a breakdown of the pattern:

  • "/" (delimiter): Indicates the start and end of the regular expression.
  • "b" (word boundary): Matches the beginning or end of a word.
  • "Hello" (pattern): The word you want to match.
  • "/" (delimiter): Indicates the end of the regular expression.

Example Implementation

Consider the following PHP code:

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

Explanation:

  • The preg_replace() function is used to perform the regular expression replacement.
  • The regular expression /bHellob/ is used to find and replace whole word matches of "Hello" with "NEW".
  • The result is stored in $newtext.

Output:

NEW hello1 hello, Helloz
Copy after login

Unicode Considerations

If your text contains Unicode characters, you may need to add the "u" modifier to the regular expression to handle non-latin characters correctly:

$newtext = preg_replace('/\bHello\b/u', 'NEW', $text);
Copy after login

The above is the detailed content of How Can I Replace Whole Words in a String Using Regular Expressions?. 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