PHP string reemplazar coincidencia de palabra completa


Me gustaría reemplazar palabras completas usando php

Ejemplo : Si tengo

$text = "Hello hellol hello, Helloz";

Y yo uso

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

El nuevo texto debería parecerse a

NUEVO hello1 hola, Helloz

PHP devuelve

NUEVO hello1 hola, NEWz

Gracias.

Author: NVG, 2010-08-06

3 answers

Desea utilizar expresiones regulares. El \b coincide con un límite de palabra.

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

Si $text contiene texto UTF-8, tendrá que agregar el modificador Unicode "u", para que los caracteres no latinos no se malinterpreten como límites de palabras:

$text = preg_replace('/\bHello\b/u', 'NEW', $text);
 54
Author: Lethargy,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-09-05 07:37:48

Palabra múltiple en cadena reemplazada por esto

    $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;
 4
Author: sandeep kumar,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-04-04 08:30:39

Array lista de reemplazo: En caso de que sus cadenas de reemplazo se sustituyan entre sí, necesita 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
);

Obviamente / para la eficiencia /\w+/ podría sustituirse por una lista de claves /\b(one|two|three)\b/i.

 1
Author: mario,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-11-23 23:49:28