我通常非常有效地解决PHP问题,但是对于这个特定问题,我似乎无法找到可行的解决方案。
我有一个由标准文本组成的$字符串,在文本中会有某些关键字被[方括号]包围,我想将其转换为链接,但这并不是将字符串与字符串进行比较的简单情况预定义的'已知'关键字数组并进行简单替换,因为[方括号]的内容可以是任何内容。
例如,我需要以下内容:
John Roberts is a jazz musician from Florida born in 1934. Some of his notable works include [A Gray Sky] and [Sophomore Effort].
应该变成以下内容:
John Roberts is a jazz musician from Florida born in 1934. Some of his notable works include <a href="search.php?search=a+gray+sky">A Gray Sky</a> and <a href="search.php?search=sophomore+effort">Sophomore Effort</a>.
应该注意:
我不是要求别人给我代码,我需要的是告诉我应该调查什么样的PHP函数并指出我正确的方向!
非常感谢你们,感谢Stackoverflow给我机会提问!
答案 0 :(得分:3)
$string = "John Roberts is a jazz musician from Florida born in 1934. Some of his notable works include [A Gray Sky] and [Sophomore Effort].";
function rep_callback($match)
{
$query = substr($match[0],1,-1);
$query = urlencode($query);
$link = '<a href="search.php?search='.$query.'">'.$match[0].'</a>';
return $link;
}
echo $string."\n";
echo preg_replace_callback("/\[.+\]/U", "rep_callback", $string)."\n";
输出:
John Roberts is a jazz musician from Florida born in 1934. Some of his notable works include [A Gray Sky] and [Sophomore Effort].
John Roberts is a jazz musician from Florida born in 1934. Some of his notable works include <a href="search.php?search=A+Gray+Sky">[A Gray Sky]</a> and <a href="search.php?search=Sophomore+Effort">[Sophomore Effort]</a>.