2009-12-18 57 views
0

比方说,我有这样的字符串: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); 

这是不完全正确的,因为搜索是贪婪的。

想法?

谢谢!

回答

2

试试这个:

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

注意:未经测试

我所做的是改变*为* ?,并关闭了你的对象标记(我认为这可能是一个错误;对不起,如果这是不正确的)。这个? 。*之后应该让它很懒。

0

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

0

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

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

我还添加“>”在表达式的末尾,以便从替换文本来避免它。

1

那么为什么不这样做水木清华这样的:

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

或者这样:

$text = preg_replace("@<object>[email protected]", "%ITEM:", $text); 
$text = preg_replace("@</object>@", "", $text); 

注:测试=)

0

那岂不是更容易在分割字符串“”的每个实例?

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