簡體   English   中英

搜索並替換為html標簽和'之外的正則表達式字母

[英]Search and replace with regex letters outside of html tags and '

我有這個PHP代碼:

$subject = "word1 <a skip this word2 >w'aot'rd2 again</a> word3";
$pattern = "~<[^>]*>|'[^>]*'(*SKIP)(*F)|o~";
$replace = 'O';
$result  = preg_replace($pattern, $replace, $subject);

echo $result;

當我在HTML標記之外將“ o”替換為“ O”時,效果很好,但我也搜索不替換“”內的“ o”。

我需要替換字母數組,例如“ r”代表“ R”,“ a”代表“ A”。

結果發現:“ wOrD1 <a skip this word2 >w'aot'rD2 again</a> wOrD3 ”在標記html之外和“之外,將” o“替換為” O“,將” d“替換為” D“。

這是只將“ o”和“ d”變為大寫的PHP代碼

$str = "word1 <a skip this word2 >w'aot'rd2 'word5' word6 'word7'</a> word3";
$re = "~(?:<[^>]*>|'[^']*')(*SKIP)(*F)|([od])~";
$str = preg_replace_callback(
    $re,
    function ($matches) {
        return strtoupper($matches[1]);
  },
  $str
);
echo $str;

如果要添加更多,只需定義自己的范圍即可。 對所有英文字符說[az]

輸出:

wOrD1 <a skip this word2 >w'aot'rD2 'word5' wOrD6 'word7'</a> wOrD3

暫無
暫無

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

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