$string = "`[code]
<p>A paragraph</p>
<script>var a = 'stackoverflow';</script>
<div id='my_div'>a block element</div>
[/code]";
preg_replace("@(<.*?>)@is","<span style='color: green;'>$1</span>");
上述preg_replace将任何<tag>
转换为绿色。然而,我只想在<tag>
包含在[code]
和[/code]
之间时执行此操作。就像上面的字符串变量。
从长远来看,regexp方法可能会变得非常乏味,或者不可能实现,这与您的技能有关。在特定情况下,它甚至会导致问题(想象一下[code][/code]=>错误中有一个绿色跨度(。
更干净的方法是解析html字符串,这样您就可以像在javascript/jQuery中那样在元素中导航。
PHP中有很多HTML解析库,我仍然使用SimpleDomParser,但你可以很容易地获得另一个。
因此,在您的情况下,首先需要提取"[code]"answers"[/code]"之间的eachs字符串,解析它们,在其中搜索有效元素,为每个找到的元素创建一个绿色跨度,然后将其移动到内部。或者类似的东西,关于你的原始数据。
这个库使用起来并不方便,但文档清晰、简洁,有很多示例。
您可以想出:
(?:
(?:'[code']
|
'G(?!'A))'s*'K)
(<([^ ]+)[^>]*>['s'S]+?</'2>)
并将其替换为<style class='someclass'>$1</style>
,请参见regex101.com上的演示。
解释
(?: # a non capturing group
(?:'[code'] # match [code]
| # or
'G(?!'A))'s*'K) # start at the previous match
# followed by whitespaces
(<([^ ]+)[^>]*>['s'S]+?</'2>) # capture html tags to group 1/2 respectively
线索是使用'G
,它允许您在上一次匹配结束时进行匹配,从而允许在类似[code]
/[/code]
的结构中寻找图案,其余部分是装饰性的(有点;-((
在
PHP
:中
$regex = '~(?:
(?:'[code']
|
'G(?!'A))'s*'K)
(<([^ ]+)[^>]*>['s'S]+?</'2>)
~x';
$string = preg_replace($regex, "<style class='someclass'>$1</style>", $your_string_here);
Demo
请参阅videone.com.