如何在方括号中查找单词并使用php转换为动态网址?

我正在尝试在[word]这样的方括号中查找单词,并创建一个动态网址。

我尝试使用str_replace()函数来查找单词,但是它会像这样创建链接

<a href="search.php?q=">word</a>

我无法将搜索到的单词添加到网址部分:

如何创建这样的真实网址?

<a href="search.php?q=word">word</a>

已更新

这是我的功能:

function findReplace($string){
    $string = str_replace ("[word]","<a href='search.php?=' title='information'>information</a>",$string); 
    return $string;
}

这是我如何从数据库获取值的方法: findReplace(htmlspecialchars($row['message']))

a692613576 回答:如何在方括号中查找单词并使用php转换为动态网址?

在这种情况下,

preg_replace是你的朋友:

$longText='bla bla [word1] bla [word2] bla [word3] bla bla';

print preg_replace('/\[(.*?)\]/','<a href="search.php?q=$1">$1</a>',$longText);

输出:

bla bla <a href="search.php?q=word1">word1</a> bla <a href="search.php?q=word2">word2</a> bla <a href="search.php?q=word3">word3</a> bla bla
本文链接:https://www.f2er.com/3107201.html

大家都在问