开发者

PHP: preg_replace() characters and make exceptions

开发者 https://www.devze.com 2023-01-16 18:14 出处:网络
I need an if() function to do this: preg_replace() letters (a, b, c, etc.) except for those wrapped in tags (<p>, <b>, <span>, etc.) and exclude the letters if they are part of a ce

I need an if() function to do this:

preg_replace() letters (a, b, c, etc.) except for those wrapped in tags (<p>, <b>, <span>, etc.) and exclude the letters if they are part of a certain word.

$string = "<p>replace everything inside tags <b>开发者_StackOverflow社区only</b> </p>exception";  
$patterns = array();  
$patterns[0] = '/e/';  
$patterns[1] = '/b/';  
$patterns[2] = '/s/';  
$replacements = array();  
$replacements[2] = '-e-';  
$replacements[1] = '-b-';  
$replacements[0] = '-s-';  
echo preg_replace($patterns, $replacements, $string);

I want "<p>", "<b>" and the word "exception" to remain unaltered.


This is almost always a bad idea to try to do in regex. You should try to use an HTML parser instead:

Robust and Mature HTML Parser for PHP

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号