git push origin master git push origin master - 10 months ago 55
PHP Question

How to grab text between multiple occurrences of tags?

i have this description that holds users mention tag.

[MENTION=1]one[/MENTION][MENTION=4]two[/MENTION][MENTION=748]three[/MENTION] HI, it is me!!

i need to know who is the members that are mentioned in this description,so i expect.


here is what i have tried:

preg_match_all('/[MENTION=[1-9]](.*?)[\/MENTION]/s', $html, $matches);
if($matches) print_r($matches[1]);


[0] => one[
[1] => [
[2] => two[
[3] => [
[4] => three[
[5] => H

What if i need to get the numbers 1,4,748 ?

Answer Source

Square brackets are reserved characters in a RegEx. You need to escape them. Something like this should work:

preg_match_all('/\[MENTION=([1-9]+)\](.*?)\[\/MENTION\]/s', $html, $matches);

I've also added a capture group around the IDs,([1-9]+), so you get the numeric values and the text-content in your matches ($matches[1] will contain the numbers and $matches[2] will contain the text-contents).