【发布时间】:2021-12-09 16:07:33
【问题描述】:
我正在尝试将 (infobox tbs7) 之类的字符串替换为 something with tbs7 之类的字符串。但即使 tbs7 是别的东西,我也希望它能够工作。我已经定义了 (infobox $) 和 something with $,但 $ 应该是任何东西。
我该怎么做?
【问题讨论】:
标签: php string str-replace
我正在尝试将 (infobox tbs7) 之类的字符串替换为 something with tbs7 之类的字符串。但即使 tbs7 是别的东西,我也希望它能够工作。我已经定义了 (infobox $) 和 something with $,但 $ 应该是任何东西。
我该怎么做?
【问题讨论】:
标签: php string str-replace
尝试将模式\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.
【讨论】:
您可以在 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 表示要替换的内容。
【讨论】: