Home > php教程 > php手册 > php获取字符串中url自动加超级链接

php获取字符串中url自动加超级链接

WBOY
Release: 2016-05-25 16:45:25
Original
2075 people have browsed it

有时我们希望用户提交的连接地址自动给这个连接加上a标签了,这个其实就是给文本url地址加超级链接了,下面整理了几个例子希望对各位会带来帮助.

PHP实例代码如下:

$string = "这是php提取文本内容字符串中的网址,连接为http://www.phprm.com 站点"; 

//连接后需要有个空格或回车。  

 
$string = eregi_replace("http://([^ ,\r\n]*)","<a href=\\0 target=_blank>\\0</a>",$string);   
$string = eregi_replace("ftp://([^ ,\r\n]*)","<a href=\\0 target=_blank>\\0</a>",$string);
Copy after login

例子1 代码如下:

<?php 
$str=&#39;这样的http://www.phprm.com/ play/?id=1010&p=1_0-1试试!&#39;; 
$pattern=&#39;/(http:\/\/|https:\/\/|ftp:\/\/)([\w:\/\.\?=&-_]+)/is&#39;; 
$str=preg_replace($pattern, &#39;<a href=\1\2>\2</a>&#39;, $str); 
echo $str; 
?>
Copy after login

例子2 代码如下:

<?php 
function autolink($foo)    
{
    $foo = eregi_replace(&#39;(((f|ht){1}tp://)[-a-zA-Z0-9@:%_/+.~#?&//=]+)&#39;, &#39;<a href="/1" mce_href="/1" target=_blank rel=nofollow>/1</a>&#39;, $foo);    
    if( strpos($foo, "http") === FALSE ){    
    $foo = eregi_replace(&#39;(www.[-a-zA-Z0-9@:%_/+.~#?&//=]+)&#39;, &#39;<a href="http:///1" mce_href="http:///1" target=_blank rel=nofollow >/1</a>&#39;, $foo);    
}else{    
    $foo = eregi_replace(&#39;([[:space:]()[{}])(www.[-a-zA-Z0-9@:%_/+.~#?&//=]+)&#39;, &#39;/1<a href="http:///2" mce_href="http:///2" target=_blank rel=nofollow >/2</a>&#39;, $foo);    
}    
return $foo;    
} 
?>
Copy after login


本文地址:

转载随意,但请附上文章地址:-)

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 Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template