【问题标题】:can't get ucfirst() to work on a variable无法让 ucfirst() 处理变量
【发布时间】:2020-11-09 17:39:21
【问题描述】:

我制作了一个代码,它从电子邮件中获取名字和姓氏,$firstname 是大写的,但 $lastname 不是。为什么?

<html>
<body>

<?php
$email = "test.testt@testing.com";
$firstname = ucfirst(strtok(strtok($email, "@"), "."));
$lastname = substr(strtok(strtok($email, "@"), ".") . ' ' . strtok("."), strrpos(strtok(strtok($email, "@"), ".") . ' ' . strtok("."), ' '));
$lastname = ucfirst($lastname);
        
echo $firstname.$lastname;
?> 
 
</body>
</html>

输出:测试 testt

任何帮助将不胜感激

【问题讨论】:

  • $lastname 以空格开头

标签: php


【解决方案1】:

除了空间的实际问题之外,您的代码还进行了大量搜索和分割字符串。

您可以通过使用explode() 来简化它,首先是@,然后是.。然后在最后一次操作的各个部分使用ucfirst...

$names = explode("@", $email);
// Get first 2 parts of name and split it by the .
[$firstname, $lastname] = explode(".", $names[0], 2);
$firstname = ucfirst($firstname);
$lastname = ucfirst($lastname);
echo $firstname . ' ' . $lastname;

【讨论】:

    【解决方案2】:

    空间确实是问题,我用$lastname = ucfirst(str_replace(' ', '', $lastname));修复了它

    【讨论】:

    • 也许 trim() 函数会成为你的朋友而不是 auf str_replace,比如 $lastname = ucfirst(trim($lastname))
    猜你喜欢
    • 2021-06-16
    • 2021-10-25
    • 1970-01-01
    • 1970-01-01
    • 2021-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-30
    • 1970-01-01
    相关资源
    最近更新 更多