Some Regex Help


I’m trying to learn some php and have hit a stumbling block on something I’m working on. I have a string that contains the following value: {Cats|Dogs|Mice} and a {Monkey|Chimp} I would like to randomly select 1 item from each group of animals. So results would look like “Cats and a Monkey” or “Mice and a Chimp” for example.

This is the code I currently have written to get started, but it’s not quite doing what I expected.

$content_str = “{Cats|Dogs|Mice} and a {Monkey|Chimp}”;
preg_match("|{(.+)}|si", $content_str, $inside);

$contents = preg_split(’/|/’, $inside[1], -1, PREG_SPLIT_OFFSET_CAPTURE);
$pieces = explode("|", $inside[1]);

$result = count($contents);
$word = $pieces[rand(0, $result-1)];
echo $inside[1];

Obviously my code is incomplete for the examples above. At this point, I was kind of expecting to see something like: “Cats|Dogs|Mice and a Monkey|Chimp” or “Cats|Dogs|Mice and a {Monkey|Chimp}”

What I’m actually getting is “Cats|Dogs|Mice} and a {Monkey|Chimp”

So my preg_match is removing the correct characters ( ‘{’ and ‘}’ ), however it’s only removing the first and the last. Ideally, I’d like for it to remove the first set only.

Any ideas about what I need to do? Hopefully this make sense.


Thank you for the fantastic (and fast!) feedback.

Given what you’ve suggested, I guessing it should look something more like this then.

[php]preg_match_all(’|({[^}]+})|’, $content_str, $inside, PREG_PATTERN_ORDER);[/php]

As for using explode, I will definitely use that moving forward. I wasn’t even aware of it’s existence.

Woops, posted my response to the wrong forum. LOL.

Anyways, in case anyone in the future needs the answer, it’s above :slight_smile:

Sponsor our Newsletter | Privacy Policy | Terms of Service