Re: Non-Greedy Regex Matching
| From: | Michael Dearman | Date: | Tue, 31 Oct 2000 15:29:51 +0000 |
| Subject: | Re: Non-Greedy Regex Matching | ||
| References: | 1 | Groups: | php.general |
| Request: | Send a blank email to php-general+get-22936@lists.php.net to get a copy of this message | ||
Matt Henderson wrote:
>
> Hello,
>
> I'm trying to replace the contents of a custom tag <pmlink>content</pmlink>
> with the following expression:
>
> $OUT = ereg_replace(
> '<pmlink>([^<]+)</pmlink>',
> $linkTemplate,
> $string);
>
> This works except that the match is 'greedy'-- e.g. the 'content' of the
> following string:
>
> <pmlink>Hello</pmlink> world <pmlink>again</pmlink>
>
> ...would incorrectly be determined as...
>
> Hello</pmlink> world <pmlink>again
>
> I tried the Perl modifier '?' as follows:
>
> $OUT = ereg_replace(
> '<pmlink>([^<]+?)</pmlink>',
> $linkTemplate,
> $string);
>
> ...and PHP4 returned a "bad regular expression" error. Does anyone on the
> list know what modifier I can use to have a non-greedy matching?
>
Your best bet is to take a look at pregs - the php version of perl regexs.
They're covered in the manual.
And if it's like the real Perl, it'll be like (?:[^<]+)
the ?: is the non-greedy thingy.
Also, I believe the pregs are faster. Don't know where I got that.
Mike D.