【问题标题】:PHP str_replace with a changeable partPHP str_replace 带有可变部分
【发布时间】:2021-12-09 16:07:33
【问题描述】:

我正在尝试将 (infobox tbs7) 之类的字符串替换为 something with tbs7 之类的字符串。但即使 tbs7 是别的东西,我也希望它能够工作。我已经定义了 (infobox $)something with $,但 $ 应该是任何东西。

我该怎么做?

【问题讨论】:

    标签: php string str-replace


    【解决方案1】:

    尝试将模式\binfobox \S+ 替换为infobox,后跟替换词:

    $input = "Here is infobox tbs7 and other things.";
    $output = preg_replace("/\binfobox \S+/", "infobox abc", $input);
    echo $output;  // Here is infobox abc and other things.
    

    【讨论】:

    • 快到了!我需要将代码输出 tbs7(无论信息框后面是什么)作为变量,以使该代码按我的意愿工作。
    【解决方案2】:

    您可以在 preg_grep 中使用正则表达式:

    $source = '(infobox tbs7)';
    $target = 'something with $2';
    $pattern = '/^(\(infobox )(.*)(\))$/i';
    $result = preg_replace($pattern, $target, $source);
    

    正则表达式模式将源字符串“拆分”为三部分:

    '(infobox '           -> $1
    'anything in between' -> $2
    ')'                   -> $3
    

    在替换字符串中使用 $2 表示要替换的内容。

    【讨论】:

    • 谢谢,但我也想在一堆文本中找到 (infobox) 的东西。如果我输入包含信息框的文本,它只会输出$source。
    • 也许你应该添加一些例子。我不太清楚源字符串是什么样的。
    猜你喜欢
    • 1970-01-01
    • 2012-01-20
    • 2014-09-29
    • 1970-01-01
    • 1970-01-01
    • 2011-08-16
    • 2021-09-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多