簡體   English   中英

PHP 字符串替換匹配整個單詞

[英]PHP string replace match whole word

我想用 php 替換完整的單詞

示例:如果我有

$text = "Hello hellol hello, Helloz";

我用

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

新文本應如下所示

NEW hello1 你好,Helloz

PHP 返回

NEW hello1 你好,NEWz

謝謝。

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

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

如果$text包含 UTF-8 文本,則必須添加 Unicode 修飾符“u”,以便非拉丁字符不會被誤解為單詞邊界:

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

字符串中的多個單詞由此替換

    $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.

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

您還可以使用T-Regx庫,在替換時引用$\\字符

<?php
$text = pattern('\bHello\b')->replace($text)->all()->with('NEW');

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM