Your Location is: Home > Php

can't get ucfirst() to work on a variable

From: Saudi View: 1662 rain 
 php

Question

I have made a code that takes the first name and last name from an email, the $firstname is uppercase but $lastname is not. Why?

<html>
<body>

<?php
$email = "[email protected]";
$firstname = ucfirst(strtok(strtok($email, "@"), "."));
$lastname = substr(strtok(strtok($email, "@"), ".") . ' ' . strtok("."), strrpos(strtok(strtok($email, "@"), ".") . ' ' . strtok("."), ' '));
$lastname = ucfirst($lastname);
        
echo $firstname.$lastname;
?> 
 
</body>
</html>

Output: Test testt

any help would be greatly appreciated

Best answer

Besides the actual problem being the space, your code does a lot of searching and chopping strings up.

You could simplify it by using explode() with first the @ and then a .. Then using ucfirst on each part of the last operation...

$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;

Another answer

The space was indeed the problem, I fixed it by using $lastname = ucfirst(str_replace(' ', '', $lastname));