简体   繁体   English

如何在PHP中用链接和标签替换纯文本URL

[英]How to replace plain text URLs with links and hashtags in PHP

I am trying to convert plain text into links, hashtags and @tags. 我正在尝试将纯文本转换为链接,主题标签和@tags。 I have managed to partially do this, but can't find any way of differentiating between a hashtag and a link containing a hash. 我已经部分地做到了这一点,但是找不到区分标签和包含哈希的链接的任何方法。

I'm new to using regex so it may be a bit messy! 我是使用regex的新手,所以可能有点混乱!

//link
$message = preg_replace('/((http(s)?)(\:\/\/)|(www\.))([a-zA-Z0-9_\-\.\/\&\%\?\=\+\#\:\;\~\[\]\!\,\@\$\'\(\)\*]+)/', '<a href="http$3://$5$6">$0</a>', $message );
//handle
$message = preg_replace('/[@]+([A-Za-z0-9-_]+)/', '<a href="#$1">$1</a>', $message );
//hashtag
$message = preg_replace('/[#]+([A-Za-z0-9-_]+)/', '<a href="#$1">$1</a>', $message );

The plain text converts to a link as desired, and then breaks at the point of the hash. 纯文本根据需要转换为链接,然后在哈希点中断。

Desired text: 所需文字:

www.hello.com/about_us/test%20page/test-page.php#header?this=12345&that=YES www.hello.com/about_us/test%20page/test-page.php#header?this=12345&that=YES

Actual text: 实际文字:

header?this=12345&that=YES">www.hello.com/about_us/test%20page/test-page.php#header?this=12345&that=YES 头?这= 12345&那= YES“> www.hello.com/about_us/test%20page/test-page.php#header?this=12345&that=YES

Is there any way of checking if the hash is part of a URL before converting it to a hashtag? 在将哈希转换为哈希标签之前,是否有任何方法可以检查哈希是否是URL的一部分?

Your regex for hashtag is this: 您的主题标签正则表达式是这样的:

/[#]+([A-Za-z0-9-_]+)/

Your stated goal is to make sure it's not part of a URL, which you identify by: 您声明的目标是确保它不是URL的一部分,您可以通过以下方式识别URL:

/https?\:\/\//

You can try to use a negative look-behind: 您可以尝试使用负向后看:

/(?<!https?\:\/\/)[^#]*[#]+([A-Za-z0-9-_]+)

This is not enough for all general cases, but it sounds like you're trying to solve a problem within a scope under your control (a text file you own or something) so hopefully this well help you. 对于所有一般情况而言,这还不够,但是听起来您正在尝试在您控制的范围内解决问题(您拥有的文本文件或其他内容),因此希望对您有所帮助。

一个对我有用的解决方案:

$message = preg_replace('/^(?<!http)^(?<!www\.)[#]+([A-Za-z0-9-_]+)/', '<a href="#$1">$1</a>', $message );//#hashtag

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM