Reprint: http://www.jb51.net/article/52916.htm
In fact, I introduced how to use PHP code in the article "Converting URL addresses in text into JavaScript and PHP custom functions for clickable links" To implement the method of converting a URL address into a link, today I will introduce to you a more concise version. Let’s take a look at the PHP source code first:
/**
* Author: SeeDZ
* From: http://code.seebz.net/p/autolink-php/
**/
function autolink($str, $attributes = array()) {
$attrs = '';
foreach ($attributes as $attribute=>$value) {
$attrs .= " {$attribute}="{$value}"";
}
$str = ' '.$str;
$str = preg_replace('`([^"='>])((http|https|ftp|ftps)://[^s< ] +[^s<.)])`i', '$1$2', $str);
$str = substr($str, 1);
return $str;
}
How about it, it’s very concise! Take a look at the API documentation of the function:
Syntax
string autolink ( string $str [ , array $attributes = array() ] )
Parameter introduction
str - required (String type data). The text that needs to be queried and replaced
attributes - optional (Array type data) to replace some optional parameters. .
Return value
Returns the replaced text.
autolink() is also very convenient to use. We can only pass one parameter, which is the required character text. For example:
$str = 'A link : http://example.com/?param=value#anchor.';
$str = autolink($str);
echo $str; // A link : http://example.com/?param=value#anchor .
?>
In addition, we can also set some additional link parameters, so that the generated link can be opened in a new window, or we do not want to search the
indexengineindexreplaced link. For example:
$str = 'http://example.com/';
$str = autolink($str, array("target"=>"_blank","rel"= >"nofollow"));
echo $str; // http://example. com/
?>
The above introduces the PHP implementation of auolink that converts URLs in text into links, including aspects of it. I hope it will be helpful to friends who are interested in PHP tutorials.