1

I have a string with multiple tags in as so:

<item>foo bar</item> <item>foo bar</item>

I need to match each of these and they can be on new lines and add them to an array, it can't seem to match them though, I'm new to regex so I'm not understanding what is going wrong, an explanation would be great, thanks!

preg_match_all('/<item>(.*)<\/item>/',$content,$matches);

At the moment, it returns two empty index in the matches array.

I have also tried:

<item>([\s\S]*)<\/item>

This matches from the first tag until the very last one, so grabs everything essentially.

5
  • Try it in this way preg_match_all('/(<item>(.*?)<\/item>)/',$content,$matches); Commented Dec 2, 2016 at 15:58
  • Possible duplicate of How do you parse and process HTML/XML in PHP? Commented Dec 2, 2016 at 16:04
  • If the question is just about regexs then .* is greedy and wants everything it can grab. Depending on what you mean by new lines this also could behave differently. There are modifiers you could use to affect these behaviors. Look at the U and s modifiers, php.net/manual/en/reference.pcre.pattern.modifiers.php. Commented Dec 2, 2016 at 16:05
  • @chris85 I can't parse it as XML as I'm adding these tags into a wysiwyg editor in Magento as a way to have dynamic content for static blocks, so essentially <p> tags get wrapped around each new line, which can't just be stripped out as they could be nested inside the content within the tags too. Commented Dec 2, 2016 at 16:08
  • What you've shown in the question can be done with a parser. Can you show more of what you are doing? Commented Dec 2, 2016 at 16:16

1 Answer 1

2

You can use this

preg_match_all('/<item>(.*?)<\/item>/',$content,$matches);

Result

 Array
 (
    [0] => Array
    (
        [0] => <item>foo bar</item>
        [1] => <item>foo bar</item>
    )

[1] => Array
    (
        [0] => foo bar
        [1] => foo bar
    )

)

I only added ? to the regex, that looks for the nearest match and get it.

Read about lazy and greedy here: What do lazy and greedy mean in the context of regular expressions?

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

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.