PHP implementation removes non site internal and external link instance code
- 2021-06-29 10:36:53
- OfStack
1 In general, when making a website system, delete links that are not local when adding articles for optimization reasons. For this requirement, you can achieve the effect of automatic deletion of external links of articles by letting PHP process the content of the following articles.
This example code mainly refers to the outer chain deletion method of the dream CMS content management system.
/**
* Remove non-site links
*
* @access public
* @param string $body content
* @param array $allow_urls Allowed hyperlinks
* @return string
*/
function Replace_Links( &$body, $allow_urls=array() )
{
$host_rule = join('|', $allow_urls);
$host_rule = preg_replace("#[\n\r]#", '', $host_rule);
$host_rule = str_replace('.', "\\.", $host_rule);
$host_rule = str_replace('/', "\\/", $host_rule);
$arr = '';
preg_match_all("#<a([^>]*)>(.*)<\/a>#iU", $body, $arr);
if( is_array($arr[0]) )
{
$rparr = array();
$tgarr = array();
foreach($arr[0] as $i=>$v)
{
if( $host_rule != '' && preg_match('#'.$host_rule.'#i', $arr[1][$i]) )
{
continue;
} else {
$rparr[] = $v;
$tgarr[] = $arr[2][$i];
}
}
if( !empty($rparr) )
{
$body = str_replace($rparr, $tgarr, $body);
}
}
$arr = $rparr = $tgarr = '';
return $body;
}