Regex Returning Too Much

Any questions involving matching text strings to patterns - the pattern is called a "regular expression."

Moderator: General Moderators

Post Reply
User avatar
revof11
Forum Newbie
Posts: 16
Joined: Tue Jan 18, 2005 7:30 am
Location: Mountain Top, PA
Contact:

Regex Returning Too Much

Post by revof11 »

OK... so let's say I have the following string:

Code: Select all

blablabla[n option1="bla"]this is my string[/n]blablabla[n option2="bla2"]this is another string[/n]blablabla
I want to use eregi in order to retrieve each of the [n]...[/n] data.
I am trying to use the following:

Code: Select all

eregi("\\[n .+\\].+\\[/n\\]", $fmt, $links);
However, the content of $links is the entire string.
Is there any easy way to say "use the shortest match available"?

Thanks,
Joe
Last edited by revof11 on Sat May 27, 2006 11:20 am, edited 1 time in total.
User avatar
sweatje
Forum Contributor
Posts: 277
Joined: Wed Jun 29, 2005 10:04 pm
Location: Iowa, USA

Post by sweatje »

First, I recommend using preg* rather than ereg*. It is faster, and a more flexible regex engine.

Here is what I believe you are asking for, expressed as a SimpleTest test:

Code: Select all

function testBbcodeishMatches() {
$str = 'blablabla[n option1="bla"]this is my string[/n]blablabla[n option2="bla2"]this is another string[/n]blablabla';
$target = array('[n option1="bla"]this is my string[/n]'
	,'[n option2="bla2"]this is another string[/n]');

preg_match_all('~(\[n\b[^\]]*\](?:(?!\[/n\]).)*\[/n\])~ms', $str, $match);

$this->assertEqual(
	$target
	,$match[1]);
}

HTH
User avatar
revof11
Forum Newbie
Posts: 16
Joined: Tue Jan 18, 2005 7:30 am
Location: Mountain Top, PA
Contact:

Post by revof11 »

That does, in fact work.
I was also JUST able to get it rolling with the following:

Code: Select all

preg_match_all('#\[n .+?\].+#', $fmt, $links);
My content of $links, however, needed to be extracted with:

Code: Select all

foreach ( $links[0] as $in )
  $collection[] = $in;
Of course, your solution is a MUCH better fit to what I was trying to accomplish.
Post Reply