PHP - preg_replace 具有多个匹配项

发布于 2024-08-15 12:00:57 字数 372 浏览 3 评论 0原文

假设我有一个像这样的字符串:

$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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

薄荷港 2024-08-22 12:00:57

试试这个:

$text = preg_replace("/<object>.*?item_id([a-zA-Z0-9]+).*?<\/object/","%ITEM:$1",$text);

注意:未经测试

我所做的是将 .* 更改为 .*?,并关闭您的对象标签(我认为这可能是一个错误;如果不正确,抱歉)。这 ? .* 之后应该让它变得懒惰。

Try this:

$text = preg_replace("/<object>.*?item_id([a-zA-Z0-9]+).*?<\/object/","%ITEM:$1",$text);

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.

断肠人 2024-08-22 12:00:57

我们可以通过使用 *? 使搜索变得非贪婪。代替*。所以最终的正则表达式变成:

$text = preg_replace("/<object.*?item_id([a-zA-Z0-9]+).*?<\/object>/","%ITEM:$1",$text);

我还添加了“>”位于正则表达式的末尾,以避免它出现在替换的文本中。

We can make the search non-greedy by using *? in place of *. So final regex becomes:

$text = preg_replace("/<object.*?item_id([a-zA-Z0-9]+).*?<\/object>/","%ITEM:$1",$text);

I have also added '>' at the end of the regex so as to avoid it from coming in the replaced text.

三岁铭 2024-08-22 12:00:57

那么为什么不这样做:

$text = preg_replace("@<object>item_id([a-zA-Z0-9]+)</object>@", "%ITEM:$1", $text);

或者像这样:

$text = preg_replace("@<object>item_id@", "%ITEM:", $text);
$text = preg_replace("@</object>@", "", $text);

注意:经过测试=)

So why not do smth like this:

$text = preg_replace("@<object>item_id([a-zA-Z0-9]+)</object>@", "%ITEM:$1", $text);

Or like this:

$text = preg_replace("@<object>item_id@", "%ITEM:", $text);
$text = preg_replace("@</object>@", "", $text);

NOTE: tested =)

冷月断魂刀 2024-08-22 12:00:57

在每个“”实例上分割字符串不是更容易吗?

$result = '';
$items = explode('<object>', $text);
foreach ($items as $item){
  $result .= '%'.str_replace('</object>', '', $item);
}
echo $result;

Wouldn't it be easier to split the string on every instance of ""?

$result = '';
$items = explode('<object>', $text);
foreach ($items as $item){
  $result .= '%'.str_replace('</object>', '', $item);
}
echo $result;
↙温凉少女 2024-08-22 12:00:57

使用 $2 作为下一个括号。

Use $2 for the next parentheses.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文