2

我通常自己解决 PHP 问题的效率很高,但是对于这个特定的问题,我似乎找不到可行的解决方案。

我有一个由标准文本组成的 $string,在文本中会有一些被 [方括号] 包围的关键字,我想将其转换为链接,但是将字符串与预定义数组进行比较并不是一个简单的例子'known' 关键字并进行简单替换,因为 [方括号] 的内容可以是任何内容。

例如,我需要以下内容:

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>.

应当指出的是:

  • $string 将包含未知数量的 [括号中的单词]。
  • 如果会引起问题,使用方括号并不是必需的,但目前在我看来这是最方便的方法。

我不是要求有人给我代码,我需要的只是有人告诉我应该研究什么样的 PHP 函数并指出正确的方向!

非常感谢大家,也感谢 Stackoverflow 让我有机会提问!

4

1 回答 1

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>.
于 2012-05-08T03:06:08.530 回答