Re: preg_match and regular expression

From: Date: Mon, 08 Dec 2003 21:44:44 +0000
Subject: Re: preg_match and regular expression
References: 1  Groups: php.general 
Request: Send a blank email to php-general+get-172178@lists.php.net to get a copy of this message
Fred wrote:
Hi I have problems with a regular expression. I have a html file like this: .... <body> <div>Hello</div> <br> <br> <div>somthing</div> <br> </body> .... And i want to use preg_match to get a list of all the <div> tags in the file: result: $list[0] = <div>Hello</div> $list[1] = <div>somthing</div> I have tryed this: preg_match('/.*(\<div\>.*\<\/div\>).*/', $contents, $list);
Your regex is matching EVERYTHING before and after the div. It's also matching the maximum of content between the div tags. Here's a better one: /(<div>.*?<\/div>/i 1) You don't need to escape the < and >. 2) The ? after .* makes it match a minimum of content between the div tags. 3) the /i matches case insensitive, meaning that DIV will be matched as well Note that this won't work quite right on nested div tags. -- paperCrane <Justin Patrin>

« previous php.general (#172178) next »