gpt4 book ai didi

php - 替换字符串中所有出现的任何括号括起来的单词

转载 作者:行者123 更新时间:2023-12-04 05:47:31 24 4
gpt4 key购买 nike

我通常自己解决 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给我提问的机会!

    最佳答案

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

    关于php - 替换字符串中所有出现的任何括号括起来的单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10491967/

    24 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com