PHP/正则表达式:用于bbcode [s]或[strike]的简单正则表达式无法正常工作 [英] PHP/Regex: simple regex for bbcode [s] or [strike] fails to work
问题描述
对于一个愚蠢的bbcode解析器,我想在其中添加两个定义,我的原始定义是preg_replace的定义:
For a silly bbcode parser I wanted to add two definitions into one, my original definition was this for preg_replace:
'#\[s\](.*?)\[/s\]#si', '<strike>\\1</strike>'
这可行,我希望用户能够使用[s]
或[strike]
来以该格式初始化文本,因此我自然地添加了这样的想法:
And this works, I wished for the user to be able to use either [s]
or [strike]
to initiate text in that format, so I naturally added something like this thinking it would work:
'#\[(s|strike)\](.*?)\[/(s|strike)\]#si', '<strike>\\1</strike>'
不幸的是,[s]
和[strike]
(正确使用)都失败了,而不是您期望的那样: 和s
(我的markdown是正确的,可以显示其真实的外观结果,无论其内部是什么,它都显示s或罢工)strike
Unfortunately that fails, instead of what you would expect, both [s]
and [strike]
(used properly) make: and s
(my markdown is correct to show its real looking result, it shows s or strike regardless of what is inside it)strike
为什么它用标签名称代替内部文本?我在s | str周围加上括号是问题吗?我可能做错了所有..
Why does it replace the inner text with the tag name instead? Is my adding parentheses around the s|strike the problem? I am probably doing this all wrong..
推荐答案
问题是您添加了两个新的正则表达式组,在开始标记中添加了(s|strike)
,在结束标记中添加了(s|strike)
.因此,在生成的代码中,您将得到s
或strike
.您可以通过使用正确的组号2
来解决此问题.
The problem is that you added two new regex groups, (s|strike)
in the opening tag and (s|strike)
in the closing tag. So inside your resulting code you will get s
or strike
. You can fix that by simply using the correct group number, 2
.
另一种方法是通过在开头添加?:
来使新组不引用,但是我想第一个解决方案更容易理解:
Another way would be to make that new groups non-referencing, by adding a ?:
to the beginning, but I guess the first solution is easier to understand:
#\[(?:s|strike)\](.*?)\[/(?:s|strike)\]#si
这篇关于PHP/正则表达式:用于bbcode [s]或[strike]的简单正则表达式无法正常工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!