Sometimes we need to filter or extract external links of html strings. Next I will introduce an href address program that uses PHP regular expressions to extract the href address from html hyperlinks.
Use the regular expression related functions of php to extract the addresses in the html hyperlink <a href = "Address"> </a>.
The Code is as follows: |
Copy code |
<? Php $ Preg = '/<.*? Href = "(.*?) ". *?> /Is '; $ Str = '<a href = "link 1"> URLNAME </a> Text Segment 1 <a href = "link 2" target = "_ blank"> URLNAME </> text section 2 <a target = "_ blank" href = "link 3"> URLNAME </a>... text Segment n '; Preg_match_all ($ preg, $ str, $ match); // search for all matches in $ str $ preg add $ match For ($ I = 0; $ I <count ($ match [1]); $ I ++) // outputs the hyperlink address one by one { Echo $ match [1] [$ I]. "<br/> "; } ?> |
Final output:
Link 1 <br/> link 2 <br/> link 3 <br/>
Attached
PHP regular expression to extract the image address code.
The Code is as follows: |
Copy code |
$ 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 = ['| "] (. *? (? : 2.16.gif |. jpg]) ['| "]. *? [/]?> /"; Preg_match_all ($ pattern, $ str, $ match ); Print_r ($ match ); |