php str_replace用不同的文本更改字符串中的相同文本

时间:2015-10-11 04:31:53

标签: php html

这是文字:

$string = "This is my car. 
my car.
Look my car.";

我想在每个句子之前和之后添加文字: 所以我的结果是:

SOME-TEXT This is my car. SOME-TEXT
SOME-TEXT my car. SOME-TEXT
SOME-TEXT Look my car. SOME-TEXT

我这样想:

$string = str_replace("my car", "SOME-TEXT my car SOME-TEXT", $string);

但我得到了结果:

<p>This is SOME-TEXT my car. SOME-TEXT</p> 
<td>SOME-TEXT my car. SOME-TEXT</td>
<h1>Look SOME-TEXT my car. SOME-TEXT<h1>

这不是我想要的!!!

有什么想法吗?!

2 个答案:

答案 0 :(得分:0)

$string = str_replace("my car.", "my car. SOME-TEXT", $string);

答案 1 :(得分:0)

这实现了你想要的:

$string = "This is my car. 
my car.
Look my car.";
define('SOME_TEXT', 'SOME-TEXT');
define('BEG', SOME_TEXT . ' ');
define('END', ' ' . SOME_TEXT);
$result = BEG . str_replace("\n", END . "\n" . BEG, $string). END;