gpt4 book ai didi

php - 什么定义了要在 preg_replace() 中替换的正则表达式部分?

转载 作者:行者123 更新时间:2023-12-04 04:52:25 25 4
gpt4 key购买 nike

我刚开始使用 PHP 正则表达式。我了解如何阅读和编写它们(不过我需要我的书,因为我还没有记住任何模式符号)。我真的很想在我的网站上为 BB 代码使用 RegExp,使用 preg_replace .

我了解参数,但我不明白的是什么定义了模式中要替换的内容?到目前为止我所拥有的:

preg_replace('/(\[url=http:\/\/.*\])/','<a href="$1">$2</a>',"[url=http://google.com]");

现在,我知道这可能不是最好的“安全”明智之举,我只是想让一些东西起作用。我匹配整个字符串...所以我得到一个链接,看起来像 mysite/[url=http://google.com] .

我阅读了有关它的 PHP 手册,但在试图吸收和理解某些内容时仍然感到头疼:
  • 什么定义了字符串中由于模式而被替换的内容?
  • 什么告诉我我的 1 美元和 2 美元等等是什么?

  • 我什至不知道他们叫什么。有人可以向我解释一下吗?

    最佳答案

    相同的替换没有错误:

    $BBlink = '[url=http://google.com]';

    $pattern = '~\[url=(http://[^] ]+)]~';
    $replacement = '<a href="$1">$1</a>';
    $result = preg_replace($pattern, $replacement, $BBlink);

    解释:

    1) 图案
    ~       # pattern delimiter
    \[ # literal opening square bracket
    url=
    ( # first capturing group
    http://
    [^] ]+ # all characters that are not ] or a space one or more times
    ) # close the capturing group
    ] # literal closing square bracket
    ~ # pattern delimiter

    2)更换
    $1引用第一个捕获组

    替代: http://www.php.net/manual/en/function.bbcode-create.php ,见第一个例子。

    关于php - 什么定义了要在 preg_replace() 中替换的正则表达式部分?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17247546/

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