将电子邮件转换为姓名的Regex

问题描述 投票:0回答:1

我想得到一些帮助,在将电子邮件地址转换为名称时,使用 preg_replace 在一个长长的文本块中。

我的邮件可以遵循两种不同的结构。

1) [email protected]

2) [email protected]

为了可能让这个问题变得更复杂,在文本中,电子邮件地址以@开头,所以例如。

The cat sat on the mat whilst @[email protected] watched in silence. 猫坐在垫子上,而@[email protected] 默默地看着。

应该是:The cat sat on the mat whilst @ watched in silence:

The cat sat on the mat whilst Firstname Lastname watched in silence. 猫坐在垫子上,而Firstname Lastname默默地看着。

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

上面的代码似乎成功地捕捉到了我需要的部分,但保留了域名。我需要删除域名,并将任何句号转换为空格。

php preg-replace
1个回答
1
投票
  1. 你的regex过于复杂,格式可以简化为: /@([^@\s]+)@[\w.\-]+/.
  2. 我很确定我知道你接下来的问题会是什么....
  3. preg_replace_callback().
  4. 和...
$in = 'The cat sat on the mat whilst @[email protected] 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:[email protected]>First Middle Last</a> watched in silence."

记住,电子邮件地址可以是... 无所不能 而这种严重的过度简化可能会有假阳性和阴性以及其他有趣的错误。


0
投票

我刚刚测试了一下,它应该可以工作。


$text="The cat sat on the mat whilst @[email protected] watched in silence @[email protected].";


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

0
投票

如果邮件中能包含 @ 并以一个可选的 @你可以让匹配的限制性更强一些,从一个可选的@开始,并添加空白处的界限。(?<!\S)(?!\S) 以防止部分匹配。

请注意 [^\s@] 本身就是一个广泛的匹配,可以匹配除@或空格字符以外的任何字符。

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

Regex演示

例如 (使用php 7.3)

$pattern = "~(?<!\S)@?([^\s@]+)@[^\s@]+(?!\S)~";
$strings = [
    "[email protected]",
    "[email protected]",
    "The cat sat on the mat whilst @[email protected] 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演示

© www.soinside.com 2019 - 2024. All rights reserved.