PHP preg_replace() 对多个项目
这就是我到目前为止所拥有的:
<?php
$text = preg_replace('/((\*) (.*?)\n)+/', 'awesome_code_goes_here', $text);
?>
我成功匹配了以下格式的纯文本列表:
* list item 1
* list item 2
我想将其替换为:
<ul>
<li>list item 1</li>
<li>list item 2</li>
</ul>
我无法理解包裹
! 有人可以帮忙吗?
并循环
编辑:解决方案如下所示...
我的代码现在显示:
$text = preg_replace('/\* (.*?)\n/', '<ul><li>$1</li></ul>', $text);
$text = preg_replace('/<\/ul><ul>/', '', $text);
就这样!
This is what I have so far:
<?php
$text = preg_replace('/((\*) (.*?)\n)+/', 'awesome_code_goes_here', $text);
?>
I am successfully matching plain-text lists in the format of:
* list item 1
* list item 2
I'd like to replace it with:
<ul>
<li>list item 1</li>
<li>list item 2</li>
</ul>
I can't get my head around wrapping <ul>
and looping through <li>
s! Can anyone please help?
EDIT: Solution as answered below...
My code now reads:
$text = preg_replace('/\* (.*?)\n/', '<ul><li>$1</li></ul>', $text);
$text = preg_replace('/<\/ul><ul>/', '', $text);
That did it!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
一种选择是简单地用
替换每个列表项,然后运行第二次替换,该替换将替换任何
没有任何内容。
One option would be to simply replace each list item with
<ul><li>list item X</li></ul>
and then run a second replace which would replace any</ul><ul>
with nothing.我知道这是一篇旧文章 - 但它需要一个解决方案。 尝试这个! :)
I know that this is an old post - but it needs a solution. Try this! :)
我不是正则表达式方面的专家,但您要做的是匹配您拥有的模式,并通过用 () 包围所需的模式将其捕获到反向引用中。 然后,您可以将 1 美元(用于第一个反向引用等)放入您的“很棒的代码部分”
Regex buddy 如果您需要更多内容,有一个关于正则表达式的非常非常棒的教程
I'm not an expert with regex's, but what you're going to want to do is match the pattern you have and capture it into a backreference by surrounding the desired pattern with ()'s. You can then place $1 (for the first back reference and so on) in your "awesome code section"
Regex buddy has a really, really awesome tutorial on regular expressions if you need more
我想这就是你想要的
I think this is what you want