Chopping characters off of strings?

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
Matt Phelps
Forum Commoner
Posts: 82
Joined: Fri Jun 14, 2002 2:05 pm

Chopping characters off of strings?

Post by Matt Phelps »

I'm looking for a way to turn long names (eg; Brandon Bergenroth) into much shorter names by removing the first name and converting it into just an initial - so my example would now be 'B Bergenroth'.

I've managed to chop the name up into two variables using the explode function but I'm not sure how I turn 'Brandon' into just 'B'.

Here's what I have so far, does anyone have the second step?

Code: Select all

$name = "Brandon Bergenroth";

$name_length = strlen($name);

if ($name_length>12)
	{
	$newname = explode(" ",$name);
	$first_name = "$newnameї0]";
	}
DSM
Forum Contributor
Posts: 101
Joined: Thu May 02, 2002 11:51 am
Location: New Mexico, USA

Post by DSM »

use

Code: Select all

$first_int = substr($first_name,0,1);
Matt Phelps
Forum Commoner
Posts: 82
Joined: Fri Jun 14, 2002 2:05 pm

Post by Matt Phelps »

Thanks :)

In case anyone is looking for a similar solution:

Code: Select all

function chopname($name)
	{
	$name_length = strlen($name);

	if ($name_length>17)
		{
		$long_name = explode(" ",$name);
		$first_name = "$long_nameї0]";
		$surname = "$long_nameї1]";
		$initial = substr($first_name,0,1);
		$short_name = array ($initial, $surname);

		$name = implode(" ", $short_name);
		}

		return $name;
}
DSM
Forum Contributor
Posts: 101
Joined: Thu May 02, 2002 11:51 am
Location: New Mexico, USA

Post by DSM »

NP...
had the same thing come up today, creating directories with user first intial and lastname as the name of the dir
User avatar
mikeq
Forum Regular
Posts: 512
Joined: Fri May 03, 2002 3:33 am
Location: Edinburgh, Scotland

Post by mikeq »

DSM wrote:NP...
had the same thing come up today, creating directories with user first intial and lastname as the name of the dir
What happens if 2 or more people have the same name?
User avatar
9902468
Forum Commoner
Posts: 89
Joined: Thu Jun 06, 2002 6:39 am
Location: Europe

Post by 9902468 »

mikeq wrote:
DSM wrote:NP...
had the same thing come up today, creating directories with user first intial and lastname as the name of the dir
What happens if 2 or more people have the same name?
Before you create you check if there is already dir with that name, if there is, put a number after the lastname. (eg. ajhonson and ajhonson1 etc...) Remember to check also if there are already same name with a number.... or you could also use in a case like this a few special characters that are allowed in directory names like ajhonson and a_jhonson.

(obvious, no?)

-9902468
Post Reply