2017-03-09 144 views
0

我試圖根據一個人的名字和姓氏創建唯一的電子郵件地址。PHP:獲取第一個字的第一個字符和第二個字符的三個字符

例如,我想從名字托馬斯·史密斯

[email protected]威廉創建像

[email protected]的電子郵件地址收費

因此,基本上第一個名字應該返回1個字符,我想從家族名稱中取三個字符。

我試圖找到一個解決方案,但它似乎像人們嘗試類似的東西,但不完全是我在找什麼。

我設法得到類似

$thename = "Peter Bonds"; $pos = stripos($thename, ' '); $themail = substr($thename, 0, $pos + 3);

努力讓姓的名字和兩個,但沒有嚴重到找到我的具體問題的解決方案。

如果有人能夠幫助解決這個問題,我將非常感激。

回答

1

使用explodestrtolowersubstr函數的溶液:

$thename = "Peter Bonds"; 
$domain = "@domain.com"; 

$name_parts = explode(" ", $thename); 
$theemail = strtolower($name_parts[0][0]. "." .substr($name_parts[1], 0, 3)). $domain; 

print_r($theemail); 

輸出:

[email protected] 

另一種替代方法可以是使用preg_replace功能單行溶液:

$theemail = strtolower(preg_replace("/^(\w)\w+\s+(\w{3})\w*$/", "$1.$2". $domain, $thename)); 

print_r($theemail); // [email protected] 
+0

我覺得正則表達式是兩個解決方案更好。 – fubar

1

您只是使用了錯誤的功能。試試這個

<?php 
    $thename = "Peter Bonds"; 
    $pos = stripos($thename, ' '); 
    $themail = strtolower(substr($thename, 0, 1).'.'.substr($thename, $pos+1, 3).'@domain.com'); 
    echo $themail; 
?> 
相關問題