Home >Backend Development >PHP Tutorial >PHP regular expression to extract href address in html hyperlink_PHP tutorial

PHP regular expression to extract href address in html hyperlink_PHP tutorial

WBOY
WBOYOriginal
2016-07-13 16:57:131071browse

Sometimes we need to filter or extract external links from HTML strings. Below I will introduce a program that uses PHP regular expressions to extract href addresses in HTML hyperlinks for your reference.

Use PHP's regular expression related functions to extract the address in the html hyperlink .

{
The code is as follows
 代码如下 复制代码

$preg='//is';

$str ='URLNAME文本段1URLNAME文本段2URLNAME...文本段n';

preg_match_all($preg,$str,$match);//在$str中搜索匹配所有符合$preg加入$match中

for($i=0;$i

{

echo $match[1][$i]."
";

}

?>

Copy code

$preg='//is';

$str ='URLNAMEText 1URLNAMEText 2< a target="_blank" href="Link 3">URLNAME...Text segmentn';

preg_match_all($preg,$str,$match);//Search for all matches in $str that match $preg and add them to $match

 代码如下 复制代码

$str='

'; 

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

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

print_r($match);

for($i=0;$i

echo $match[1][$i]."
";

}?> Final output: Link 1
Link 2
Link 3
Attached is a PHP regular expression code to extract image address.
The code is as follows Copy code
$str='

'; $pattern="/<[img|IMG].*?src=['|"](.*?(?:[.gif|.jpg]))['|"].*?[ /]?>/"; preg_match_all($pattern,$str,$match); print_r($match); http://www.bkjia.com/PHPjc/631538.htmlwww.bkjia.comtruehttp: //www.bkjia.com/PHPjc/631538.htmlTechArticleSometimes we need to filter or extract external links from html strings. Below I will introduce an extraction using PHP regular expressions. The href address program in html hyperlinks, for your reference. The correct way to use php...

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn