RE: [PHP] preg_replace wierdness

From: Date: Sat, 23 Nov 2002 00:55:27 +0000
Subject: RE: [PHP] preg_replace wierdness
References: 1  Groups: php.general 
Request: Send a blank email to php-general+get-125696@lists.php.net to get a copy of this message
> Code snippet -> > <?php > > header('Content-type: text/plain'); > > $foo = '<img src="images/php.png"> <img > src="images/apache.png">'; > > echo "$foo\n"; > > > $path = '../../../'; > $bar = preg_replace('/(<img src=")(.*">)/', "$1" . $path . > "$2", $foo); > > echo $bar; It's being greedy. Your pattern is matching (<img src=") & (images/php.png"> <img src="images/apache.png">) and inserting $path between the two. Use $bar = preg_replace('/(<img src=")(.*">)/U',"$1" . $path . "$2", $foo); Quote: U (PCRE_UNGREEDY) This modifier inverts the "greediness" of the quantifiers so that they are not greedy by default, but become greedy if followed by "?". It is not compatible with Perl. It can also be set by a (?U) modifier setting within the pattern. ---John Holmes...

« previous php.general (#125696) next »