正则表达式将电子邮件转换为名称



我在一长段文本中使用preg_replace将电子邮件地址转换为姓名方面得到了一些帮助。

我的电子邮件可以遵循两种不同的结构:

1( firstname.lastname@domain.co.uk

2( firstname.middlename.lastname@domain.co.uk

为了使这更加复杂,在文本电子邮件地址中以@开头,例如:

猫坐在垫子上,而@firstname.lastname@domain.co.uk 默默地看着。

应该是:

猫坐在垫子上,而姓氏则默默地看着。

preg_replace("/B@(w*[a-z_.]+w*)/i", "$1", $text)

上面的代码似乎成功捕获了我需要的位,但保留了域。我需要删除域并将任何句点转换为空格。

  1. 您的正则表达式过于复杂,格式可以简化为:/@([^@s]+)@[w.-]+/.
  2. 我很确定我知道你的下一个问题是什么......
  3. preg_replace_callback().
  4. 和。。。
$in = 'The cat sat on the mat whilst @first.middle.last@domain.co.uk watched in silence.';
var_dump(
preg_replace_callback(
'/@([^@s]+)@[w.-]+/',
function($in) {
$parts = explode('.', $in[1]);
$parts = array_map('ucfirst', $parts);
$name = implode(' ', $parts);
$email = substr($in[0], 1);
return sprintf('<a href="mailto:%s>%s</a>', $email, $name);
},
$in
)
);

输出:

string(118) "The cat sat on the mat whilst <a href="mailto:first.middle.last@domain.co.uk>First Middle Last</a> watched in silence."

OFC请记住,电子邮件地址几乎可以是任何东西,这种严重的过度简化可能会出现误报/误报和其他有趣的错误。

我刚刚测试过这个,它应该可以工作


$text="The cat sat on the mat whilst @firstname.middlename.lastname@domain.co.uk watched in silence @firstname.lastname@domain.co.uk.";

echo preg_replace_callback("/B@([a-zA-Z]*.[a-zA-Z]*.?[a-zA-Z]*)@[a-zA-Z.]*./i", function($matches){
$matches[1] = ucwords($matches[1], '.');
$matches[1]= str_replace('.',' ', $matches[1]);
return $matches[1].' ';
}, $text);
// OUTPUT: The cat sat on the mat whilst Firstname Middlename Lastname watched in silence Firstname Lastname

如果电子邮件可以包含@并以可选的@开头,则可以使匹配更加严格,从可选的@开始,并在(?<!S)(?!S)添加空格边界以防止部分匹配。

请注意,[^s@]本身就是与除 @ 或空格字符之外的任何字符匹配的广泛匹配

(?<!S)@?([^s@]+)@[^s@]+(?!S)

正则表达式演示

例如(使用 php 7.3(

$pattern = "~(?<!S)@?([^s@]+)@[^s@]+(?!S)~";
$strings = [
"firstname.lastname@domain.co.uk",
"firstname.middlename.lastname@domain.co.uk",
"The cat sat on the mat whilst @firstname.lastname@domain.co.uk watched in silence."
];
foreach ($strings as $str) {
echo preg_replace_callback(
$pattern,
function($x) {
return implode(' ', array_map('ucfirst', explode('.', $x[1])));
},
$str,
) . PHP_EOL;
}

输出

Firstname Lastname
Firstname Middlename Lastname
The cat sat on the mat whilst Firstname Lastname watched in silence.

Php 演示

最新更新