首页 > 解决方案 > 从字符串中删除电子邮件地址

问题描述

我有一段

@test@gmail.com @test1@gmail.com Lorem Ipsum 只是印刷和排版行业的虚拟文本。自 1500 年代以来,Lorem Ipsum 一直是行业的标准虚拟文本,当时一位不知名的印刷商采用了一种类型的厨房并将其加扰以制作一本类型样本书。它不仅经历了五个世纪,而且经历了电子排版的飞跃,基本保持不变。它在 1960 年代随着包含 Lorem Ipsum 段落的 Letraset 表格的发布而流行起来,最近还通过 Aldus PageMaker 等桌面出版软件

所以我想从这一段中提取电子邮件并将电子邮件发送给提取的用户,并将段落的其余部分作为消息。所以我提取电子邮件并发送消息,但我的问题是该段仍然有电子邮件。我做了以下

 $pattern = '/[a-z0-9_\-\+\.]+@[a-z0-9\-]+\.([a-z]{2,4})(?:\.[a-z]{2})?/i';
    preg_match_all($pattern, $comment, $matches);
    $email=implode("\n", $matches[0]);
  
    str_replace($email, '', $comment);

预期的消息正文=

Lorem Ipsum 只是印刷和排版行业的虚拟文本。自 1500 年代以来,Lorem Ipsum 一直是行业的标准虚拟文本,当时一位不知名的印刷商采用了一种类型的厨房并将其加扰以制作一本类型样本书。它不仅经历了五个世纪,而且经历了电子排版的飞跃,基本保持不变。它在 1960 年代随着包含 Lorem Ipsum 段落的 Letraset 表格的发布而流行起来,最近还通过 Aldus PageMaker 等桌面出版软件

标签: php

解决方案


我建议像这样分解段落以检查每个元素是否包含@并将其远程放入$arr_email。我不使用正则表达式。

$my_paragraph =  "@test@gmail.com @test1@gmail.com  Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker"
$arr_email = [];
$arr_message = explode(" ", $my_paragraph);

foreach($arr_message as $key=>value) {

if(strpos($value, "@")  !== FALSE) {
  array_push($arr_email, $value);
  unset($arr_message[$key];
}

$my_paragraph = implode(" ", $arr_message);

推荐阅读