1

I wish to make something that cuts the name to e.g:

Alex Andersson

to uppercase first word after space(first name) "A" like this:

Alex A.

Right now it displays the full name like this:

echo $data["full_name"]; 

Hope you understand what I mean.

0

8 Answers 8

2

You described it vaguely, but as I understand that, you can do something like:

$names = explode(" ", $data["full_name"]);
foreach ($names as $key => $name)
{
  if ($key == 0)
    continue;
  $names[$key] = substr($name, 0, 1).'.';
} 
echo implode(" ", $names);

This shortens every name except first one.

1

You would have to store the first name and last name in different variables, as you can never tell at what position the second name would be.

You can access the first letter of a variable using square brackets.

$data[0];
0

For only two names

preg_replace('/^([A-Z][a-z]+)\s([A-Z])([a-z]+)$/', "\$1 \$2.", $data["full_name"])
0

Untested:

shortened = substr($data["full_name"], 0, strpos($data["full_name"], " ") + 1) + ".";
0

Simple and clear:

list($forename, $surname) = explode(' ', $data['full_name']);
echo $forename . ' ' . $surname[0] . '.';
0
list($fname, $sname) = explode(' ', $data["full_name"]);
$sname = strtoupper(substr($sname, 0, 1));
$new_name = $fname . $sname . '.';
0
$name = "Alex Andersson";
$name_arr =  explode(" ", $name);
echo ucfirst($name_arr[0])." ".strtoupper($name_arr[1][0]);
0
$nameParts = explode(' ', $data['full_name']);
$lastName = substr(array_pop($nameParts), 0, 1) . '.';
$firstNames = implode(' ', $nameParts);

echo $firstNames . ' ' . $lastName;
2
  • I receive Warning: substr() expects parameter 3 to be long, string given in at the lin $lastName
    – Karem
    Aug 16, 2010 at 13:20
  • Sorry, mixed up the parameters, fixed now. Aug 16, 2010 at 13:48

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.