Replace only whole word matches in a string [duplicate]
Asked Answered
U

4

39

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.

Unfriended answered 6/8, 2010 at 17:37 Comment(0)
D
75

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);
Dennett answered 6/8, 2010 at 17:43 Comment(3)
This matches mother in mother-in-law 😿 – Unpretentious
A fix for the above case might be here: https://mcmap.net/q/409384/-how-to-make-word-boundary-b-not-match-on-dashes – Unpretentious
what if we want to replace same world from whole sting more than once – Shanghai
C
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.
Cottonmouth answered 4/4, 2017 at 8:30 Comment(0)
E
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.

Endothelioma answered 23/11, 2017 at 17:46 Comment(3)
you have a syntax error , replace the last braces with parenthesis of preg_replace – Acetophenetidin
also, the if (isset($pairs[$m[0]]) doesnot have the cosing parenthesis. – Acetophenetidin
Thank you. I was looking exactly for this. – Atmo
I
0

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

<?php
$text = pattern('\bHello\b')->replace($text)->all()->with('NEW');
Ideology answered 12/12, 2018 at 17:26 Comment(0)

© 2022 - 2024 β€” McMap. All rights reserved.