PHP:获取第一个字的第一个字符和第二个字符的三个字符
问题描述:
我试图根据一个人的名字和姓氏创建唯一的电子邮件地址。PHP:获取第一个字的第一个字符和第二个字符的三个字符
例如,我想从名字托马斯·史密斯
或
[email protected]威廉创建像
[email protected]的电子邮件地址收费
因此,基本上第一个名字应该返回1个字符,我想从家族名称中取三个字符。
我试图找到一个解决方案,但它似乎像人们尝试类似的东西,但不完全是我在找什么。
我设法得到类似
$thename = "Peter Bonds"; $pos = stripos($thename, ' '); $themail = substr($thename, 0, $pos + 3);
努力让姓的名字和两个,但没有严重到找到我的具体问题的解决方案。
如果有人能够帮助解决这个问题,我将非常感激。
答
使用explode
,strtolower
和substr
函数的溶液:
$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]
答
您只是使用了错误的功能。试试这个
<?php
$thename = "Peter Bonds";
$pos = stripos($thename, ' ');
$themail = strtolower(substr($thename, 0, 1).'.'.substr($thename, $pos+1, 3).'@domain.com');
echo $themail;
?>
我觉得正则表达式是两个解决方案更好。 – fubar