PHP:将一个字段一分为二
由于许多人建议我将名字和姓氏分开,而不是“全名”,我如何将它们分开到每个变量,所以如果您在字段中输入:“Dude Jackson”,那么“Dude”进入 $firstname 和$lastname 中的杰克逊。
As many recommend me to separate firstname and lastname instead of "full_name" with everything in, how can I separate them to each variables, so if for you example type in the field: "Dude Jackson" then "Dude" gets in $firstname and Jackson in the $lastname.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
不可能做到 100% 准确,因为名字/姓氏比单个“全名”包含更多信息。 (全名可以包括中间名、缩写、头衔等,顺序有多种。)
如果您只需要快速修复旧数据库,则可以用第一个空格分隔。
It's impossible to do with 100% accuracy, since the first/last name contains more information than a single "full name". (A full name can include middle names, initials, titles and more, in many different orders.)
If you just need a quick fix for a legacy database, it might be OK to split by the first space.
假设名字总是排在前面并且没有中间名:
这只是将
$full_name
分解为包含两个字符串(如果它们仅由一个空格分隔)的数组,并将它们映射到名字和姓氏变量分别。Assuming first name always comes first and there's no middle name:
This simply explodes
$full_name
into an array containing two strings if they're separated by only one space, and maps them to the first and last name variables respectively.您可以这样做:
这假设您的全名包含由单个空格分隔的名字和姓氏。
编辑:
如果姓氏不存在,上述方法会发出
未定义偏移量
警告。为了克服这个问题,您可以使用以下替代方法:You can do:
This assumes that you full name contains first name and last name separated by single space.
EDIT:
In case the lastname is not present, the above method give a warning of
undefined offset
. To overcome this you can use the alternative method of:您需要使用空格作为分隔符将值分解为多个部分
http:// php.net/manual/en/function.explode.php
you would need to explode the value into its parts using a space as the separator
http://php.net/manual/en/function.explode.php
我不是 PHP 程序员,但为了快速修复,不丢失数据,
这应该将名称的所有剩余部分保存在 $lastname 中,对于像“Roelof van der Merwe”这样的名称应该有帮助。您还可以检查 $full_name 仅作为名字,不包含姓氏。
I am no PHP programmer, but for a quick fix, without data loss,
This should save all remaining part of name in $lastname, should be helpful for names like "Roelof van der Merwe". Also you can throw in checks for $full_name as first name only, without last name.
这是代码/解决方案
This is the code/solution