View Full Version : reverse strings.
11-20-2011, 03:00 PM
Hi I was wondering if someone could help me figure out how to use name strings obtained using substr() to create a new reverse name string? for example
firstname surname reversed to surname, firstname?? adding a comma and space in between??
11-20-2011, 05:14 PM
Can you provide the code used to obtain the name via SubStr()?
11-20-2011, 05:28 PM
$fullname = "Helen Conor";
$len = strlen($fullname);
$firstname = substr($fullname, 0, 6);
$secondname = substr($fullname, 7, 15);
print "firstname is $firstname and secondname is $secondname";
11-20-2011, 05:29 PM
$name = 'firstname surname';
$name = preg_split( '/\s+/', $name, 2, PREG_SPLIT_NO_EMPTY );
$name = array_reverse( $name );
$name = implode( ', ', $name );
echo $name; // surname, firstname
The big gotcha with this solution is that it will take anything before the first space as the first name, and everything else is the last name.
So with the name Billy Joe Smith, the first name will be Billy, and the surname will be Joe Smith... when we would expect the first name to be Billy Joe.
11-20-2011, 06:52 PM
This will over come the two first name problem and works with one first name:
$name = 'Billy Joe Smith';
echo strrchr($name,' ').', '.trim(str_replace(strrchr($name,' '), '', $name));
For clarity the last name is can be found with
$last = strrchr($name,' ');
before the substitution.
11-21-2011, 02:52 AM
Keep in mind the last name can possibly be more than one word:
$name = 'Billy Joe Smith, Jr.';
$last = strrchr( $name, ' ' );
echo $last; // Jr.
...which is what I was alluding to in my first reply. You may have it work on 95% of two-word names out there, but there will always be the possibility of a two-word first name, last name, or both.
Powered by vBulletin® Version 4.2.2 Copyright © 2017 vBulletin Solutions, Inc. All rights reserved.