0

我有一个 .txt 文件,我想用新字符串替换第一次出现子字符串后出现的所有内容。

例如,如果 .txt 文件包含:

这是彼得,他喜欢巧克力派。外面阳光明媚。

我希望能够用“酒吧”替换世界“巧克力”之后的所有内容,所以最终结果将是:

这是彼得,他喜欢巧克力棒

最好的方法是什么?

4

2 回答 2

2

一个preg_replace电话将起作用:

$subject = "This is Peter and he likes chocolate pies. It's sunny outside.";
$regex = "#(chocolate).+$#";
$out = preg_replace($regex,"$1 bars.",$subject);

如果需要,您可以用变量替换搜索模式和替换模式中的单词。

于 2013-07-30T22:29:02.807 回答
2

使用 strpos 和 substr 的混合来切断末端。

$str = 'This is Peter and he likes chocolate pies. It\'s sunny outside.';
$find = 'pies';
$replace = 'bars';
$str = substr($str, 0, strpos($str, $find)) . $replace;
于 2013-07-30T22:29:22.517 回答