首页 > 解决方案 > 使用 PHP/laravel 8 抓取字符串中的标签

问题描述

我正在使用 PHP/Laravel 8,我正在尝试获取字符串的每个标签(以 # 开头的单词)并编辑字符串以在其中设置锚点。

例如:

$string = "Hello, this is a #string with multiples #tags";

//方法

=> $newString = "Hello, this is a <a href='/string'>#string</a> with multiples <a href='/tags' >#tags</a>"

我尝试了很多东西,但从那一刻起我就卡住了......

谢谢你的帮助...

标签: phplaravellaravel-blade

解决方案


使用preg_replace()

#[^ ]+

演示

$string = "Hello, this is a #string with multiples #tags";

echo preg_replace('/#([^ ]+)/', '<a href="/$1">$0</a>', $string);

推荐阅读