3 回答

TA貢獻1831條經驗 獲得超4個贊
您的正則表達式過于復雜,格式可以簡化為:
/@([^@\s]+)@[\w.\-]+/
.我很確定我知道你接下來的問題是什么......
preg_replace_callback()
.和...
$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."
并且要記住,電子郵件地址幾乎可以是任何東西,這種粗暴的過度簡化可能會產生誤報/漏報和其他有趣的錯誤。

TA貢獻1856條經驗 獲得超5個贊
如果電子郵件可以包含@
并以可選的 開頭@
,您可以使匹配更加嚴格,以可選的 @ 開頭并添加空格邊界(?<!\S)
以(?!\S)
防止部分匹配。
請注意,[^\s@]
它本身是一個廣泛匹配,可以匹配除 @ 或空白字符之外的任何字符
(?<!\S)@?([^\s@]+)@[^\s@]+(?!\S)
例如(使用 php 7.3)
$pattern = "~(?<!\S)@?([^\s@]+)@[^\s@]+(?!\S)~";
$strings = [
"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.

TA貢獻1777條經驗 獲得超10個贊
我剛剛測試過這個,它應該可以工作
$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
- 3 回答
- 0 關注
- 187 瀏覽
添加回答
舉報