38

I would like to replace just complete words using php

Example : If I have

$text = "Hello hellol hello, Helloz";

and I use

$newtext = str_replace("Hello",'NEW',$text);

The new text should look like

NEW hello1 hello, Helloz

PHP returns

NEW hello1 hello, NEWz

Thanks.

NVG
  • 3,248
  • 10
  • 40
  • 60

4 Answers4

74

You want to use regular expressions. The \b matches a word boundary.

$text = preg_replace('/\bHello\b/', 'NEW', $text);

If $text contains UTF-8 text, you'll have to add the Unicode modifier "u", so that non-latin characters are not misinterpreted as word boundaries:

$text = preg_replace('/\bHello\b/u', 'NEW', $text);
Josh Davis
  • 28,400
  • 5
  • 52
  • 67
Lethargy
  • 1,859
  • 14
  • 15
8

multiple word in string replaced by this

    $String = 'Team Members are committed to delivering quality service for all buyers and sellers.';
    echo $String;
    echo "<br>";
    $String = preg_replace(array('/\bTeam\b/','/\bfor\b/','/\ball\b/'),array('Our','to','both'),$String);
    echo $String;
    Result: Our Members are committed to delivering quality service to both buyers and sellers.
Sandeep Sherpur
  • 2,418
  • 25
  • 27
2

Array replacement list: In case your replacement strings are substituting each other, you need preg_replace_callback.

$pairs = ["one"=>"two", "two"=>"three", "three"=>"one"];

$r = preg_replace_callback(
    "/\w+/",                           # only match whole words
    function($m) use ($pairs) {
        if (isset($pairs[$m[0]])) {     # optional: strtolower
            return $pairs[$m[0]];      
        }
        else {
            return $m[0];              # keep unreplaced
        }
    },
    $source
);

Obviously / for efficiency /\w+/ could be replaced with a key-list /\b(one|two|three)\b/i.

mario
  • 144,265
  • 20
  • 237
  • 291
0

You can also use T-Regx library, that quotes $ or \ characters while replacing

<?php
$text = pattern('\bHello\b')->replace($text)->all()->with('NEW');
Danon
  • 2,771
  • 27
  • 37