首页 > 解决方案 > PHP替换字符串的一部分并将这些替换的部分作为单独的字符串

问题描述

我有一个像这样的字符串,"[one]sdasf[two]sad[three]"

因此,我想将 [one] 替换为"replaced_one",将 [two] 替换为"replaced_two"。我需要那些替换的值作为单独的字符串。

$rep_one = "replaced_one";
$rep_two = "replaced_two";

标签: phpstringstr-replace

解决方案


这是一个简单的 PHP 函数str_replace()(有关更多信息,请转到PHP 手册

该函数需要三个参数:

str_replace(
  # Search - string section to be replaced
  # Replace - the content which will replace the `Search`
  # Subject - The string you want to alter
)

所以在你的情况下,你可以简单地这样做:

$str = "[one]sdasf[two]sad[three]";
$str = str_replace('[one]', 'replace_one', $str);
$str = str_replace('[two]', 'replace_two', $str);

echo $str; // replace_onesdasfreplace_twosad[three]

推荐阅读