PHP Regular expression extracts the href address in an HTML hyperlink

Source: Internet
Author: User
Tags php regular expression preg

Use PHP's regular expression correlation function to extract HTML hyperlink <a href= address in "address" ></a>

<?php

$preg = '/<a. *?href= ' (. *?) ". *?>/is ';

$str = ' <a href= ' link 1 >URLNAME</a> text segment 1<a href= "Link 2" target= "_blank" >URLNAME</a> text segment 2<a target= "_blank" href= "link 3" >URLNAME</A> Text Segment n ';

Preg_match_all ($preg, $str, $match);//Search in $STR matches all $preg join $match

for ($i =0; $i <count ($match [1]), $i + +)//Output hyperlink address one by one

{

echo $match [1][$i]. " <br/> ";

}

?>

Final output:

Link 1<br/> link 2<br/> link 3<br/>

Attached to a

PHP's regular expression extracts the code for the image address.

$str = ' <p style= ' padding:0px; margin-top:0px; margin-bottom:0px; line-height:200%; " ></p><p style= "padding:0px; margin-top:0px; margin-bottom:0px; line-height:200%; " ></p><p style= "padding:0px; margin-top:0px; margin-bottom:0px; line-height:200%; " ></p> ";

$pattern = "/<[img| Img].*?src=[' | "] (.*? (?: [. gif|. JPG])) [' | ']. *? [/]?>/];

Preg_match_all ($pattern, $str, $match);

Print_r ($match);

PHP Regular expression extracts the href address in an HTML hyperlink

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.