PHP Realizes the Method of Filtering External Links of Site Content

  • 2021-07-18 07:14:54
  • OfStack

Friends who are familiar with SEO know that if the link has rel= "nofollow" attribute, unnecessary losses can be avoided when the external link of the website fails. This paper demonstrates the filtering method of external links of site content by PHP in the form of examples. The details are as follows:

Problem Description: Originally, many articles in the station are excerpted external articles, and many links in the articles are either invalid for a long time, or they are 1 test website, such as http://localhost/, etc. If there are many links, many dead links in the station will be formed, which is very unfavorable to SEO optimization.

Solution: Content within the site needs to be filtered, adding the rel = "nofollow" attribute to links that are not internal links.

This article draws lessons from wordpress's function of filtering external links, and can be used by changing it to 1.

The specific code is as follows:


// External links increase nofllow $content  Content  $domain  Current website domain name 
function content_nofollow($content,$domain){
 preg_match_all('/href="(.*?)"/',$content,$matches);
 if($matches){
 foreach($matches[1] as $val){
  if( strpos($val,$domain)===false ) $content=str_replace('href="'.$val.'"', 'href="'.$val.'" rel="external nofollow" ',$content);
 }
 }
 preg_match_all('/src="(.*?)"/',$content,$matches);
 if($matches){
 foreach($matches[1] as $val){
  if( strpos($val,$domain)===false ) $content=str_replace('src="'.$val.'"', 'src="'.$val.'" rel="external nofollow" ',$content);
 }
 }
 return $content;
}

It is very good to call when calling, as shown below


$a['content'] = content_nofollow($a['content'],$domain);  // Add links to the content of the article nofllow Attribute 


Attention! The domain name filtered here needs to be without "/", such as https://www. ofstack. com, so that it can be filtered well.

I believe the method described in this paper has a certain reference value for everyone's PHP project development.


Related articles: