Reputation: 319
I researched quite a long time before posting, but I couldn't come up with an answer.
I'm trying to remove all characters but the first from a string. The string is going to be a name. The name can have a first name and a last name, as well as a middle name. So my task is to explode the string into words and find the last one, remove the characters and add a dot to the first letter. Moreover, if present in the string, the middle name should not be in the result.
For example: Chuck Ray Norris
should transform into Chuck N.
I tried a couple of regex
and strpos
but this task is too difficult for me and my skills.
Upvotes: 0
Views: 985
Reputation: 1085
Alternatively, if it is just a string with the requirements:
Chuck Ray Norris -> Chuck N
Then using explode(), substr() and strlen():
<?php
$string = "Chuck Ray Norris";
// break string into words
$array = explode(" ", $string);
// keep the first word, keep the last word's first character
// ensure we have broken into vaid parts
$length = count($array);
if($length > 2) {
// ie. Chuck Norris
$first_word = $array[0];
$last_word = $array[$length-1];
// get first character,
$first_character = substr($last_word, 0, 1);
}
// else case is omitted
print "$first_word $first_character\n"; // outputs Chuck N
?>
string substr ( string $string , int $start [, int $length ] )
Ex: substr($last_word, 0, 1)
int $start
: the length of "Norris" is 6, so first position is 0 int $length
: we need only 1 character, therefore position 0, "N"; Hope this helps.
Upvotes: 0
Reputation: 1668
This is how I would do it:
$pos = strrpos($string, " ");
$pos = $pos === false ? 0 : $pos + 1;
$char = substr($string,$pos,1);
Upvotes: 0
Reputation: 3148
i don't know if this will work, but try this
<?php
$fullName = 'Chuck Ray Norris';
//$fullName = 'Chuck Ray';
//$fullName = 'Chuck';
$names = explode(' ', $fullName);
if((count($names) == 3) && isset($names[2])){
echo $names[0] . ' ' . $names[2][0] . '.';
}else{
if((count($names) == 2) && isset($names[1])){
echo $names[0] . ' ' . $names[1][0] . '.';
}else{
echo $names[0];
}
}
?>
try to change the $fullName to 'Chuck Ray' or 'Chuck' its still working also.
Upvotes: 0
Reputation: 626699
A non-regex solution for "FirstName SecondName ThirdName... LastName" pattern:
<?php
$str = "Chuck Ray Norris";
$spls = explode(" ", $str);
echo $spls[0] . " " . $spls[count($spls)-1][0] . ".";
Output:
Chuck N.
Upvotes: 2
Reputation: 784958
You can use:
$s = 'Chuck Ray Norris';
$r = preg_replace('/^(\S+)\s+(?:\S+\s+)*(\S)\S*$/', '$1 $2.', $s);
//=> Chuck N.
$s = 'Chuck Norris';
$r = preg_replace('/^(\S+)\s+(?:\S+\s+)*(\S)\S*$/', '$1 $2.', $s);
//=> Chuck N.
$s = 'Chuck N.';
$r = preg_replace('/^(\S+)\s+(?:\S+\s+)*(\S)\S*$/', '$1 $2.', $s);
//=> Chuck N.
(?:\S+\s+)*
is used for making 1 or more middle names optional. It also takes care of the case when name is already in desired format (case 3 above).
Upvotes: 2