Home > Backend Development > PHP Tutorial > PHP implements auolink that converts URLs in text into links

PHP implements auolink that converts URLs in text into links

WBOY
Release: 2016-07-29 09:14:43
Original
1783 people have browsed it

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

index

engineindexreplaced 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.

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template