php Code:
$txt =
preg_replace( '~<a([^>]+)~i',
'<a\\1 target="_blank"',
$txt );
Fixed. I left the closing sign out of my pattern because it matches up until then anyways, so why waste the two extra bytes I figure.
I've memorized most of the symbols at this point. Ranges, quantifiers, characters and anchors are all pretty straight forward once you've used them a few times. What I need to learn next myself is assertations. While I can honestly say I've managed to create some pretty useful expressions without them, I really think learning them will take things up a level. They seem straightforward enough but I've just never put them into practice yet.
php Code:
// For example, this matches <a href=""> but excludes <a name="">$txt =
preg_replace( '~<a\s+(?!name)([^>]+)>~i',
'<a \\1 target="_blank">',
$txt );
Which is nice if all of your anchors are formed in the order you expect them to be, such as
a href, or
a name, but if somebody decided to use the format
a class="" name="" then the above will match it and add the target attribute. So once again, while the expression has gotten smarter, it's still not smart enough.
There's a good cheat sheet over at
addedbytes.com, and some great writeups at
regular-expressions.info