PHP获取某个单词或短语前后的文本


PHP Get text before and after a certain word or phrase

我有电子邮件进入邮箱,我正在使用PHP函数imap_open来获取电子邮件。

每封电子邮件看起来都像:

您收到来自447的新消息***,上面写着谢谢。:)您可以回复此电子邮件,它将被转换为短信!如果你需要回复你的电子邮件到短信,那么要么购买一个专用的回复号码,要么将你的默认sendername设置为Simple replies(设置->E2S)在回复末尾键入##,以防止转换不需要的文本(例如签名、广告、免责声明、以前的回复文本)。非常感谢Textlocal.com团队。*

所以我想得到真正的信息。在上面的例子中,消息是:

Thank you :)

我怎么能只收到这部分电子邮件?

假设每条消息的前缀/后缀是恒定数量的字符(如您在问题中所述)

这是一个q&d的答案,所以我不会计算两个字符串中的确切字符数。假设第一个字符串中有10个字符要剥离,第二个字符串中则有150个字符。中间的字符是你的信息:

$msg = 'You have a new message from 447*** saying Thank you. :) You may reply to this email and it will be converted into an SMS text message! If you need replies back to your email to SMS messages then either purchase a dedicated reply number, or set your default sendername to Simple Replies (Settings->E2S) Type ## at the end of the reply to prevent unwanted text being converted (e.g. signature, advert, disclaimers, previous reply text). Many thanks, the Textlocal.com team.*';
$msg = substr(substr($msg, 0, -150),10);
echo $msg;

如果字符数不是恒定的,那么您必须首先使用strpos()来找到消息的所需部分开始/结束的位置,然后在上面的代码中使用这些数字。


好吧,我必须测试一下,所以我最后数了数。操作线路为:

$msg = substr(substr($msg, 0, -417), 42);

可以用双引号(")或任何其他符号转义消息。这使解析更容易。示例:

$string = 'You have a new message from 447*** saying "Thank you. :)" You may reply...';
$string = explode('"', $string);
echo $string[1];

它返回谢谢:)。

您可以为此使用正则表达式:

$pattern = '~message from 'd{6} saying (.*) You may~';
if(preg_match($pattern, $text, $matches)) {
    $message = $matches[1];
}
echo $message;

在上面的正则表达式中,'d{6}应该与电话号码相匹配。CCD_ 4需要相应地改变。

输出:

Thank you. :)

在线演示

不使用正则表达式:

$message = "You have a new message..."; // this is the message you receive.
$par1 = explode("saying ", $message); // temp variable
$par2 = explode(" You may reply", $par1[1]); // another temp variable
$text = $par2[0]; // this is the text you wanted to get.

par1par2不是必需的,像这样的单一线性

$text = explode(" You may reply", explode("saying ", $message)[1])[0];

在我这边工作得很好,但看起来你的文本编辑器不知怎么发现了语法错误,所以我更新了我的代码。