制作php正则表达式代码synthax highlighter $string=“`[code]
段落 var a=‘stackoverflow’; 块元素 [/代码]”;制作php正则表达式代码synthax highlighter $string=“`[code],php,regex,Php,Regex,段落 var a=‘stackoverflow’; 块元素 [/代码]”; preg_replace(“@(.*is)”,“$1”) 上述preg_replace将任何转换为绿色。但是,我只想在包含在[code]和[/code]之间时执行此操作。与上面的字符串变量类似。您可以得出: $string = "`[code] <p>A paragraph</p> <script>var a = 'stackoverflow';</script> <
preg_replace(“@(.*is)”,“$1”)代码>
上述preg_replace将任何
转换为绿色。但是,我只想在
包含在[code]
和[/code]
之间时执行此操作。与上面的字符串变量类似。您可以得出:
$string = "`[code]
<p>A paragraph</p>
<script>var a = 'stackoverflow';</script>
<div id='my_div'>a block element</div>
[/code]";
演示
请参阅。从长远来看,就您的技能而言,regexp方法可能会变得非常单调乏味,甚至不可能实现。在特定情况下,它甚至可能导致问题(假设[code][/code]=>错误中有一个绿色范围)
一种更干净的方法是解析html字符串,这样您就可以像在javascript/jQuery中一样在元素中导航
PHP中有许多HTML解析库,我仍在使用,但您可以轻松地获取另一个
因此,在您的情况下,首先需要提取“[code]”和“[/code]”之间的eachs字符串,解析它们,搜索其中的有效元素,为找到的每个元素创建一个绿色的跨度,然后将其移到内部。
或者类似的,关于你的原始数据
这个库使用起来并不方便,但是它清晰、简洁,有很多示例。这可以通过JavaScript或jQuery而不是regex来操作DOM。我有一个工作的JavaScript模型。使用getElementsByTagName('code');for循环和“replace”功能。它工作得很好。我试图通过使用php和regex.com扩展我的范围。也许您可以找到正则表达式的其他应用程序。
(?:
(?:\[code\]
|
\G(?!\A))\s*\K)
(<([^ ]+)[^>]*>[\s\S]+?</\2>)
(?: # 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
$regex = '~(?:
(?:\[code\]
|
\G(?!\A))\s*\K)
(<([^ ]+)[^>]*>[\s\S]+?</\2>)
~x';
$string = preg_replace($regex, "<style class='someclass'>$1</style>", $your_string_here);