PHP 正则表达式替换
我目前正在尝试使用 PHP 将令牌添加到 CMS。
用户可以输入(到所见即所得编辑器中)一个字符串,例如[my_include.php]
。我们希望提取具有这种格式的任何内容,并将其转换为以下格式的包含:
include('my_include.php');
任何人都可以协助编写正则表达式和提取过程以允许此操作?理想情况下,我想将它们全部提取到一个数组中,以便我们可以在将其解析为 include();
? 之前提供一些检查。
谢谢!
I am currently trying to add tokens to a CMS using PHP.
The user can enter (into a WYSIWYG Editor) a string such as [my_include.php]
. We would like to extract anything with this format, and turn it into an include of the following format:
include('my_include.php');
Can anyone assist with composing the RegExp and extraction process to allow this? Ideally, I would like to extract them all into a single array, so that we can provide some checking before parsing it as the include();
?
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
工作示例:http://ideone.com/zkwX7
Working sample: http://ideone.com/zkwX7
您要么想要使用 preg_match_all(),在循环中运行结果并替换您找到的任何内容。可能比下面的回调解决方案快一点,但如果使用 PREG_OFFSET_CAPUTRE 和 substr_replace() 则有点棘手。
You'll either want to go with preg_match_all(), run the results in a loop and replace whatever you found. Might be a bit faster than the following callback solution, but is a bit more tricky if PREG_OFFSET_CAPUTRE and substr_replace() is used.
使用
preg_match_all()
,你可以这样做:这里使用的正则表达式是
\[.+\.php\]
。这将匹配任何*.php
字符串,因此如果用户键入[hello]
,它将不匹配。Using
preg_match_all()
, you could do this:The regex used here is
\[.+\.php\]
. This will match any*.php
string so that if the user types[hello]
for example, it won't match.