2010-08-06 184 views
25

我想使用PHPPHP字符串替換全字匹配

實例只替換完整的話: 如果我有

$text = "Hello hellol hello, Helloz"; 

我用

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

新案文應看起來像

新hello1 hell O,Helloz

PHP返回

新hello1你好,NEWz

感謝。

回答

48

你想使用正則表達式。 \b匹配單詞邊界。

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

如果$text包含UTF-8文本,你必須添加Unicode修改的 「u」,使非拉丁字符不會被誤解爲單詞邊界:

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

字符串多字換成這個

$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; 
1

Array替換列表:如果替換字符串互相替換,則需要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 
); 

顯然/效率/\w+/可以用一個密鑰列表/\b(one|two|three)\b/i更換。

+0

你有一個語法錯誤,用'preg_replace'的括號替換最後一個大括號' – 2017-11-23 23:23:51

+0

也'if(isset($ pairs [$ m [0]])'沒有cosing括號。 – 2017-11-23 23:29:51

+0

回收我的 - 1票這現在看起來不錯 – 2017-11-24 17:18:44