PHP - preg_replace 具有多个匹配项
假设我有一个像这样的字符串:
$text = "<object>item_id1a2b3</object>xxx<object>item_id4c5d6</object>"
我想将其转换为: %ITEM:1a2b3xxx%ITEM:4c5d6
这是我得到的:
$text = preg_replace("/<object.*item_id([a-zA-Z0-9]+).*<\/object/","%ITEM:$1",$text);
这不太正确,因为搜索是贪婪的。
想法?
谢谢!
Let's say I have a string like:
$text = "<object>item_id1a2b3</object>xxx<object>item_id4c5d6</object>"
I want to convert it to:
%ITEM:1a2b3xxx%ITEM:4c5d6
Here's what I've got:
$text = preg_replace("/<object.*item_id([a-zA-Z0-9]+).*<\/object/","%ITEM:$1",$text);
This isn't quite right, as the search is greedy.
Thoughts?
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
试试这个:
注意:未经测试
我所做的是将 .* 更改为 .*?,并关闭您的对象标签(我认为这可能是一个错误;如果不正确,抱歉)。这 ? .* 之后应该让它变得懒惰。
Try this:
NOTE: Untested
What I did was change the .* to .*?, and to close off your object tag (I thought that might have been a mistake; sorry if that's not correct). The ? after the .* should make it lazy.
我们可以通过使用 *? 使搜索变得非贪婪。代替*。所以最终的正则表达式变成:
我还添加了“>”位于正则表达式的末尾,以避免它出现在替换的文本中。
We can make the search non-greedy by using *? in place of *. So final regex becomes:
I have also added '>' at the end of the regex so as to avoid it from coming in the replaced text.
那么为什么不这样做:
或者像这样:
注意:经过测试=)
So why not do smth like this:
Or like this:
NOTE: tested =)
在每个“”实例上分割字符串不是更容易吗?
Wouldn't it be easier to split the string on every instance of ""?
使用
$2
作为下一个括号。Use
$2
for the next parentheses.