1

I've got string like

$content = "Some content some content
[images ids="10,11,20,30,40"]
Some content";

I want to remove [images ids="10,11,20,30,40"] part from it and get ids part as php array(10,11,20,30,40)

Is it possible with regex?

5
  • Have you tried anything? Code please. Commented Dec 3, 2013 at 19:01
  • I've made string replace and then array explode by comma, but I dont think it is good solution. Commented Dec 3, 2013 at 19:02
  • 3
    @Kluska000 if you know the format of your string, then what you're doing sounds like a good idea to me Commented Dec 3, 2013 at 19:03
  • Yeah, that's what anyone is going to do... Commented Dec 3, 2013 at 19:04
  • You probably can't do both those things with a single preg function. Commented Dec 3, 2013 at 19:08

2 Answers 2

6

You can use this:

$txt = <<<LOD
Some content some content
[images ids="10,11,20,30,40"]
Some content
LOD;

$result = array();

$txt = preg_replace_callback('~(?:\[images ids="|\G(?!^))([0-9]+)(?:,|"])~',
    function ($m) use (&$result) { $result[] = $m[1]; }, $txt);
        
echo $txt . '<br>' . print_r($result, true);

The \G anchor can be very useful in this situation since it's a kind of anchor that means "at the start of the string or contiguous to a precedent match".

However, nothing in the pattern checks if there is a last number followed by "]. If you need to do that, you must add a lookahead to the pattern:

~(?:\[images ids="|\G(?!^))([0-9]+)(?=(?:,[0-9]+)*"])(?:,|"])~
Sign up to request clarification or add additional context in comments.

2 Comments

@anubhava: Thanks anubhava! The \G feature is like a philosopher's stone, you search it for a long time, but it's very powerful.
Yes I learnt about \G in one of your previous answers sometime back. Thanks!
2

Assuming that's the structure of content and it doesn't get any more complex, then:

preg_match_all('/(\d+)/', $content, $matches);
print_r($matches[0]);

More would need to be added to narrow it down if it is more complex.

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.