Could someone please help me make my php regex less greedy? I need to insert code for an onclick event into the midst of a bunch of tags, and can't get it to work.
bah... it's stripping out my less-than and greater-than signs, so I'm afraid this is incomprehensible.
$teaser = preg_replace("less-thana (.+?) greater-than", "$1 code insertion",$teaser); posted by teaperson at 3:09 PM on December 5, 2006
Replace the .+ with [^>]+
You could also just search and replace <a with <a onclick="blah" and forget the regex posted by cillit bang at 3:44 PM on December 5, 2006
(though processing HTML with regexes will never be particularly reliable) posted by cillit bang at 3:45 PM on December 5, 2006
Greediness isn't your problem. Delimiters are. You're writing a different expression than you think. PCRE expressions require delimiters. Your expression's delimiters are the lessthan/greaterthan signs, so the regex is looking for any instance of "a" followed by a space then at least one other character.
Here's something more specific, and case insensitive. Run the example with your original expression to understand the difference.
<?php
$teaser="a banana is not a <A HREF='foo'>link</A>";
$teaser = preg_replace("/<a (.+?)>/i", "<a $1 Hi!>",$teaser);
print $teaser;
?> posted by nakedcodemonkey at 6:31 PM on December 5, 2006
« Older
I would like to setup a webcam...
| While I was in Stockholm, Swed...
Newer »
$teaser = preg_replace("less-thana (.+?) greater-than", "$1 code insertion",$teaser);
posted by teaperson at 3:09 PM on December 5, 2006