PHP - preg_replace with multiple matches
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:1a2b3xx开发者_JAVA百科x%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!
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.
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.
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 =)
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;
Use $2
for the next parentheses.
精彩评论