PHP - 将字符串中的字符串替换为另一个字

时间:2018-04-03 11:47:09

标签: php

我在变量中有一个字符串,例如:

$example1 = "Received: from example.host.com (example.host.com [1.2.3.4]) by received.host.com (Postfix) with ESMTP id 123456789ABCD for ; Tue, 3 Apr 2018 12:33:59 +0200 (CEST)"

$example2 = "Received: from another.example.org (unknown [22.33.44.55]) by another.received.org (Postfix) with ESMTP id 987654321FEDC for ; Tue, 3 Apr 2018 12:35:15 +0200 (CEST)"

我希望使用模式by替换for...之间的所有内容

所以 example1 应该是:

"Received: from example.host.com (example.host.com [1.2.3.4]) by ... for ; Tue, 3 Apr 2018 12:33:59 +0200 (CEST)"

example2 应为:

"Received: from another.example.org (unknown [22.33.44.55]) by ... for ; Tue, 3 Apr 2018 12:35:15 +0200 (CEST)"

唯一的问题是(因为邮件仇恨者)“by”和“for”之间的所有内容都可以更改,它将永远不会相同。示例中的其他所有内容必须保持不变。

2 个答案:

答案 0 :(得分:0)

<?php
$string = "Received: from another.example.org (unknown [22.33.44.55]) by another.received.org (Postfix) with ESMTP id 987654321FEDC for ; Tue, 3 Apr 2018 12:35:15 +0200 (CEST)";
$x = strpos($string,'by');
$y = strpos($string,'for');
echo substr($string, 0, $x+2)."...".substr($string, $y);
?>

答案 1 :(得分:-1)

使用示例

<?php
echo str_replace("world","Peter","Hello world!");
?>