2

Good day.

I'm having a problem with a pattern.

Let's assume I have a string like this:

Hello [person]Name[/person], I don't know regex like [person]Another_name[/person] does.

I need to preg_split this string to get an array like this:

Array(0 => 'Name', 1 => 'Another_name');

I've been trying to solve this for some time and still no luck.

Pardon for my ignorance. Any kind of help is kindly appreciated.

Maxim R
  • 78
  • 1
  • 6
  • 2
    Use preg_match_all instead of preg_split. – nhahtdh Jan 31 '13 at 14:33
  • Can we assume that there will never be any variation in the syntax of `[person]` (ie it will always look as shown in the question; no additional attributes or anything like that), and that there will be no possibility of nested tags? If we can assume that, it's not too hard. – SDC Jan 31 '13 at 14:33
  • * See also [Open source RegexBuddy alternatives](http://stackoverflow.com/questions/89718/is-there) and [Online regex testing](http://stackoverflow.com/questions/32282/regex-testing) for some helpful tools, or [RegExp.info](http://regular-expressions.info/) for a nicer tutorial. – mario Jan 31 '13 at 14:40
  • thanks a lot! solution was to use preg_match_all instead of preg_split – Maxim R Jan 31 '13 at 14:55

1 Answers1

4

You'll want to use something like preg_match_all instead of preg_split:

preg_match_all("|\[person\](.*)\[/person\]|U",
    "Hello [person]Name[/person], I don't know regex like [person]Another_name[/person] does.",
    $out);

echo $out[1][0] . ", " . $out[1][1] . "\n";

You can learn more about how $out is structured here: http://www.php.net/manual/en/function.preg-match-all.php

Joseph Erickson
  • 2,304
  • 20
  • 29