Igor Simic
7 years ago

How to find and attach target blank to all href links from text using PHP


In this example we will search for all  <a href links inside of content ad check do they have target="_blank"atribute, if they don't have we will attach it:

public static function format_input_text($content){
        
        // find all links
         preg_match_all('/<a ((?!target)[^>])+?>/', $content, $href_matches); 

        /* example output
			array (
			  0 => 
			  array (
			    0 => '<a href="https://sourceforge.net/projects/pcre/files/pcre/8.38/">',
			    1 => '<a href="http://www.mzan.com/article/35986243-error-when-using-regexp-in-mysql.shtml">',
			    2 => '<a href="https://community.apachefriends.org/f/viewtopic.php?f=29&amp;t=74101">',
			  ),
			  1 => 
			  array (
			    0 => '"',
			    1 => '"',
			    2 => '"',
			  ),
			) 

        */

        // loop only first array to modify links
        foreach ($href_matches[0] as $key => $value) {

        	// take orig link
        	$orig_link = $value; 

        	// does it have target="_blank"
        	if (!preg_match('/target="_blank"/',$orig_link)){

        		// add target = "_blank"
        		$new_link = preg_replace("/<a(.*?)>/", "<a$1 target=\"_blank\">", $orig_link); 


        		// replace old link in content with new link
        		$content =str_replace($orig_link, $new_link, $content);

        	}
  
        }
 
        

        return $content;

    }