views:

301

answers:

5

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!

A: 

Use $2 for the next parentheses.

sakabako
+1  A: 

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.

mabwi
A: 

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

$text = preg_replace("//","%ITEM:$1",$text);

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

RahulJ
A: 

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 =)

Wizzard
A: 

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;
qualbeen