php html 从文本创建链接

2021-12-22 00:00:00 text php html

我找到了在文本中找到链接时创建 html 链接的例程

I found a routine to create a html link when a link is found in a text

 <?php
 function makelink($text) 
 {
 return preg_replace('/(http://[a-zA-Z0-9_-.]*?) /i', '<a href="$1">$1</a> ', $text." "); 
 } 

 // works
 echo makelink ("hello how http://www.guruk.com ");

 // dont work
 echo makelink ("hello how http://www.guruk.com/test.php ");

?>

如您在示例中所见,它仅适用于域,而不适用于该链接中存在页面或子目录的情况.

as you see in the example, it works find with a domain only, not when there is a page or subdirectory is within that link.

您能否为该功能提供一个解决方案,使其也适用于页面和子目录?

Can you provide a solution for that function to work also with pages and subdirs?

谢谢克里斯

推荐答案

字符 ?=& 用于带有查询字符串的 url.请注意,我将分隔符从 / 更改为 ! 因为您的表达式中有很多斜线.另请注意,如果您处于不区分大小写的模式,则不需要 A-Z.

The characters ?=& are for urls with query strings. Notice that I changed the separator from / to ! because there a lot of slashes in your expression. Also note that you don't need A-Z if you are in case-insensitive mode.

return preg_replace('!(http://[a-z0-9_./?=&-]+)!i', '<a href="$1">$1</a> ', $text." ");

相关文章