0

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!

5 Answers 5

2

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.

Sign up to request clarification or add additional context in comments.

Comments

2

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.

Comments

1

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

Comments

0

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;

Comments

0

Use $2 for the next parentheses.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.