faqts : Computers : Programming : Languages : PHP : Common Problems : Regular Expressions

+ Search
Add Entry AlertManage Folder Edit Entry Add page to http://del.icio.us/
Did You Find This Entry Useful?

27 of 34 people (79%) answered Yes
Recently 7 of 10 people (70%) answered Yes

Entry

What is the best PHP regular expression to match an anchor tag?

Jun 12th, 1999 07:00
Nathan Wallace, Martin B. Jespersen, thejedi.com


Try this regular expression:

"<a[ ]{0,}href=[\"']{0,}([a-zA-Z0-9/:~._#]{0,})[\"']{0,}>([^<]{0,})</a>"

For example, you want to change some HTML so that links are displayed
for printing.

You have a line that looks like so:
$a = 'stuff <a href="http://www.somewhere.com">Link to
Somewhere</a>stuff';
 
You want to change it to:
'stuff <U>Link to Somewhere</U>&LT;http://www.somewhere.com&GT;'

You can use:

eregi_replace(
    "<a[
]{0,}href=[\"']{0,}([a-zA-Z0-9/:~._#]{0,})[\"']{0,}>([^<]{0,})</a>",
    "<U>\\2</U>&LT;\\1&GT;",
    $a);

http://www.php.net/manual/function.eregi-replace.php3