Regex Heck
December 5, 2006 3:06 PM Subscribe
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.
Here's the code I have:
$teaser = preg_replace("", "$1 code insertion",$teaser);
Any changes I could think of produce errors.
PHP is the only programming language I have access to.
Here's the code I have:
$teaser = preg_replace("", "$1 code insertion",$teaser);
Any changes I could think of produce errors.
PHP is the only programming language I have access to.
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
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
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.
posted by nakedcodemonkey at 6:31 PM on December 5, 2006
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 X-Mas webcam open to the world. | Why was a bus loads of Swedish teens dressed in... Newer »
This thread is closed to new comments.
$teaser = preg_replace("less-thana (.+?) greater-than", "$1 code insertion",$teaser);
posted by teaperson at 3:09 PM on December 5, 2006