PHP/Regex: simple regex for bbcode [s] or [strike] fails to work

Deadly 提交于 2019-11-29 23:29:52

问题


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>'

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>'

Unfortunately that fails, instead of what you would expect, both [s] and [strike] (used properly) make: s and strike (my markdown is correct to show its real looking result, it shows s or strike regardless of what is inside it)

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..


回答1:


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


来源:https://stackoverflow.com/questions/4245008/php-regex-simple-regex-for-bbcode-s-or-strike-fails-to-work

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!