Re: eregi question

From: Date: Mon, 26 Jun 2000 20:16:32 +0000
Subject: Re: eregi question
References: 1  Groups: php.general 
Request: Send a blank email to php-general+get-3192@lists.php.net to get a copy of this message
> Taking my first hectic foray into Regular Expression stuff... > > $message=eregi_replace("<center>([[:alnum:]|[:space:]|[:punct:]]*)</center>","<tag>\\1</tag>",$messa ge); > > Using the PHP eregi functions, I've been trying to capture everything > between <center>and </center> - however, as you can probably see, this > doesn't quite work like it's supposed to. For instance: > > <center> Bob </center> <b> Alice </b> <center> Bob > </center> > > Actually ends up returning this: > > <tag> Bob </center> <b> Alice </b> <center> Bob </tag> > > Does anyone know how I can work around this problem? I've tried > different variations of "any character class , but NOT EQUAL to </center>" > but my syntax seems to be off. You've run into a problem with greedy matching. One way would be to rewrite that expression like you tried (e.g. <center>([^<]+)</center> with a really nasty expression). Alternatively, use the Perl-compatible regular expressions. preg_match will take a modifier (U) that tells it not to be greedy. This means that it will return the first match, not the match which covers the largest part of the input: echo "PCRE result: " . preg_match('/<center>(.+)<\/center>/U', '<center>foo</center><center>bar</center>', $parts); echo '<PRE>'; echo htmlspecialchars($parts[1]); echo '</PRE>';

« previous php.general (#3192) next »