我有这个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;
当我更换&#34; o&#34;它可以正常工作为&#34; O&#34;在HTML标签之外,但我搜索的不是替换&#34; o&#34;里面的&#39;&#39;同样。
我需要更换字母数组,例如&#34; r&#34;为&#34; R&#34;和&#34; a&#34;为&#34; A&#34;。
结果查找:&#34; wOrD1 <a skip this word2 >w'aot'rD2 again</a> wOrD3
&#34;替换&#34; o&#34;为&#34; O&#34;和&#34; d&#34;对于&#34; D&#34;,在标签html之外以及&#39;&#39;
答案 0 :(得分:2)
以下PHP code仅将“o”和“d”转换为大写:
$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;
如果您想添加更多内容,只需定义自己的范围即可。对所有英文字符说[a-z]
。
输出:
wOrD1 <a skip this word2 >w'aot'rD2 'word5' wOrD6 'word7'</a> wOrD3