Tags
PHP
Asked 3 years ago
9 Jun 2021
Views 315
Mahesh Radadiya

Mahesh Radadiya posted

string replace match whole word in php

string replace match whole word in php
andy

andy
answered Apr 25 '23 00:00

In PHP, you can use regular expressions with the preg_replace() function to replace a whole word in a string. Here is an example:



$text = "The quick brown fox jumps over the lazy dog";
$wordToReplace = "quick";
$newWord = "slow";
$result = preg_replace("/\b$wordToReplace\b/", $newWord, $text);
echo $result; // Outputs: "The slow brown fox jumps over the lazy dog
"
In the regular expression, the \ b matches a word boundary. By enclosing the word to replace and the new word in \b , we ensure that only whole words are matched and replaced.

If you want to replace all occurrences of the word, not just whole words, you can use the str_replace() function instead. Here is an example:



$text = "The quick brown fox jumps over the quick dog";
$wordToReplace = "quick";
$newWord = "slow";
$result = str_replace($wordToReplace, $newWord, $text);
echo $result; // Outputs: "The slow brown fox jumps over the slow dog"
Post Answer