首页 > 解决方案 > 无法让 ucfirst() 处理变量

问题描述

我制作了一个代码,它从电子邮件中获取名字和姓氏,$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

任何帮助将不胜感激

标签: php

解决方案


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

您可以先使用explode()with@再使用 a来简化它.。然后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;

推荐阅读