且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

解析主题标签的文本并使用 php 替换为链接

更新时间:2023-12-05 15:53:58

试试这个:

$text = "Vivamus #tristique non elit eu iaculis.";$text = preg_replace('/(?:^|\s)#(\w+)/', ' <a href="tag/$1">$1</a>', $text);//$text now: Vivamus <a href="tag/tristique">tristique</a>非欧盟精英;

它正在运行:https://3v4l.org/WXqTr(点击运行).

正则表达式参考:空格或字符串开头非捕获组

原始来源:使用 RegExp 解析 Twitter

I have some text with twitter style #hashtags. How would I write a function to parse a body of text that might contain an unlimited number of #hashtags, take the text of the hashtag and replace them all with an <a href="tag/[hashtag text]">[hashtag text]</a>

I've thought a lot about how to do this but I am really bad at writing these sorts of functions with regex.

Example text:

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus #tristique non elit eu iaculis. Vivamus eget ultricies nisi. Vivamus hendrerit at mauris condimentum scelerisque. Donec nibh mauris, pulvinar et #commodo a, porta et tellus. Duis eget ante gravida, convallis augue id, blandit lectus. Mauris euismod commodo mi ut fringilla. Sed felis magna, rhoncus vitae mattis varius, sagittis a eros. Donec eget porta ipsum. #Mauris sed mauris ante. Suspendisse potenti. Donec a #pretium #augue, eget hendrerit orci. Integer cursus scelerisque consequat.

Try using this:

$text = "Vivamus #tristique non elit eu iaculis.";
$text = preg_replace('/(?:^|\s)#(\w+)/', ' <a href="tag/$1">$1</a>', $text);
// $text now: Vivamus <a href="tag/tristique">tristique</a> non elit eu iaculis;

Here it is working: https://3v4l.org/WXqTr (click run).

Regex reference: Space or beginning of string, Non capturing group

Original source: Parsing Twitter with RegExp