php - regex to match div tags -
i'm using regex match specific div's in page , replace them custom formatted one. can't use domdocument pages process mal-formed , after running through domdocument, pages reformatted , don't display same.
i'm using following works perfectly:
preg_match('#(\<div id=[\'|"]'.$key.'[\'|"](.*?)\>)(.*?)\<\/div\>#s', $contents, $response);
to match div tags such as:
<div id="test"></div> <div id="test" style="width: 300px; height: 200px;"></div> etc...
the problem i'm encountering tags id after style or class, example:
<div class="test" id="test"></div>
if run following, regex seems become greedy , matches ton of html before div tag, i'm not sure how fix this:
preg_match('#(\<div(.*?)id=[\'|"]'.$key.'[\'|"](.*?)\>)(.*?)\<\/div\>#s', $contents, $response);
does have ideas?
you can use ungreedy modifer (u
), , - not use .*
, [^>]*
(which means not > > end of tag , searching withing tag). don't need escape / when not delimiter (you using # delimiter)
preg_match('#(<div[^>]*id=[\'|"]'.$key.'[\'|"][^>]*>)(.*)</div>#isu', $contents, $response);
Comments
Post a Comment