替换字符串中的两个单词(PHP)

时间:2013-08-14 09:30:31

标签: php string

我需要用字符串中的一个单词替换两个单词。例如,我的字符串如下:

$mySentence = "abcd efg ijkl";
$replaceWith = "XYZ";
$newString = str_replace("efg ijkl", $replaceWith, $mySentence);

但是没有任何改变。

输出应为abcd XYZ。

4 个答案:

答案 0 :(得分:2)

$mySentence = "abcd efg ijkl";
$replaceWith = "XYZ";
$newString = str_replace("efg ijkl", $replaceWith, $mySentence);
echo $newString;

此输出

abcd XYZ

答案 1 :(得分:1)

  

但是没有任何改变。

更改,但您只是不输出它才能看到。您为$newString分配了替换文本,但从未显示新字符串。

所以,正如人们回答的那样,你只需要输出变量。可以echovar_dump()

echo $newString

会给你

abcd XYZ

答案 2 :(得分:0)

代码:

<?php
$mySentence = "abcd efg ijkl";
$replaceWith = "XYZ";
$newString = str_replace("efg ijkl", $replaceWith, $mySentence);
echo $newString;
?>

答案 3 :(得分:0)

 $mySentence = "abcd efg ijkl";
 $replaceWith = "XYZ";
 $newString = preg_replace("/efg ijkl/", $replaceWith, $mySentence);
 print_r($newString);

输出:

abcd XYZ
相关问题