3 回答
TA贡献1831条经验 获得超4个赞
您的正则表达式过于复杂,格式可以简化为:
/@([^@\s]+)@[\w.\-]+/
.我很确定我知道你接下来的问题是什么......
preg_replace_callback()
.和...
$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."
并且要记住,电子邮件地址几乎可以是任何东西,这种粗暴的过度简化可能会产生误报/漏报和其他有趣的错误。
TA贡献1856条经验 获得超5个赞
如果电子邮件可以包含@
并以可选的 开头@
,您可以使匹配更加严格,以可选的 @ 开头并添加空格边界(?<!\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.
TA贡献1777条经验 获得超10个赞
我刚刚测试过这个,它应该可以工作
$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
- 3 回答
- 0 关注
- 151 浏览
添加回答
举报