繁体   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