[SOLVED]Stripping a string down to the first chars of each w

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
User avatar
batfastad
Forum Contributor
Posts: 433
Joined: Tue Mar 30, 2004 4:24 am
Location: London, UK

[SOLVED]Stripping a string down to the first chars of each w

Post by batfastad »

Hi guys

I'd like to know the best way to extract the first characters of each word in a string.

This would have 2 uses - converting people's names to initials, and also converting a string into an abbreviation.

The way I thought of doing it is...

Code: Select all

$string = 'John McGee';
$string_exp = explode(' ', $string);

foreach ($string_exp as $key => $word) {
     $abbr .= substr($word, 0, 1);
}

echo strtoupper($abbr);
But I'm not sure if this is the best way of doing things.
Is there a quicker / more efficient way I'm missing here?


Thanks

Ben
Last edited by batfastad on Wed Nov 01, 2006 4:39 am, edited 1 time in total.
User avatar
volka
DevNet Evangelist
Posts: 8391
Joined: Tue May 07, 2002 9:48 am
Location: Berlin, ger

Post by volka »

Code: Select all

$pattern = '!(?<=\s|^)(\S)!';
$subject = 'Mary had a little lamb, its fleece was white as snow';

preg_match_all($pattern, $subject, $matches);
foreach($matches[1] as $m) {
	echo "'", $m, "' <br />\n";
}
I don't know if it's more efficient but it's different ;)
Superman859
Forum Commoner
Posts: 47
Joined: Sun Oct 29, 2006 10:22 am

Post by Superman859 »

I thought of doing it the same way you did, although I'm not sure if it is the best (I just started learning PHP last week).

One thing to note...if you are not dealing with keys, you don't need to write $key.

Code: Select all

$string = 'John McGee'; 
$string_exp = explode(' ', $string); 

foreach ($string_exp as $word) { 
     $abbr .= substr($word, 0, 1); 
} 

echo strtoupper($abbr);
However, from what I understand, if you continue with another string (for example if you made a loop and were going to get the initials of many users), you would want to reset $abbr each time. Otherwise it would continue adding on to the first initials/etc. I could be wrong, I'm just beginning, but I do come from having a strong Java background.

I also believe you could do the following...

Code: Select all

$string = 'John McGee'; 
$string_exp = explode(' ', $string); 

foreach ($string_exp as $word) { 
     $abbr .= $word{0}; //I believe this is similar to charAt() in other languages...returns the character at given position.
} 

echo strtoupper($abbr);
User avatar
Weirdan
Moderator
Posts: 5978
Joined: Mon Nov 03, 2003 6:13 pm
Location: Odessa, Ukraine

Post by Weirdan »

here's another idea:

Code: Select all

$abbr = join(
          '', 
          array_filter(
             preg_split(
                 '//', 
                 ucwords(
                     strtolower($string)
                 )
             ), 
            'ctype_upper'
          )
        );
User avatar
batfastad
Forum Contributor
Posts: 433
Joined: Tue Mar 30, 2004 4:24 am
Location: London, UK

Post by batfastad »

Superman859 wrote:One thing to note...if you are not dealing with keys, you don't need to write $key.
Yep, well spotted!
Was just testing :lol:
Superman859 wrote:However, from what I understand, if you continue with another string (for example if you made a loop and were going to get the initials of many users), you would want to reset $abbr each time. Otherwise it would continue adding on to the first initials/etc. I could be wrong, I'm just beginning, but I do come from having a strong Java background.
Again, yep. I will do that, as I'll set this up as a function.
Superman859 wrote:$abbr .= $word{0}; //I believe this is similar to charAt() in other languages...returns the character at given position.
Out of all these different suggestions, explode() seems the simplest one.
I try to steer clear of regular expressions unless they're absolutely needed as I always thought there's a processing overhead, but also because I don't understand regex syntax :lol:

Anyone have any info on this type of syntax?
Where would I find it in the PHP manual?

I'm assuming that since this syntax seems to be a language construct, it should give better performance than using a function like substr()?

Not that it really matters for such a small function. Just like to know I'm doing things the best way!!


Thanks for all your help everyone!!!

Ben
printf
Forum Contributor
Posts: 173
Joined: Wed Jan 12, 2005 5:24 pm

Post by printf »

One more way...

Code: Select all

<?php

$string = 'John McGee';

echo implode ( ' ', array_map ( create_function ( '$v', 'return $v[0] . ".";' ), explode ( ' ', $string ) ) );

?>
printf
User avatar
Jenk
DevNet Master
Posts: 3587
Joined: Mon Sep 19, 2005 6:24 am
Location: London

Post by Jenk »

and another..

Code: Select all

$string = 'The Quick Brown Fox Jumped Over The Lazy Dog.';

echo preg_replace('/[a-z.,!\?]+\s?/m', '', $string);

//output: TQBFJOTLD
User avatar
volka
DevNet Evangelist
Posts: 8391
Joined: Tue May 07, 2002 9:48 am
Location: Berlin, ger

Post by volka »

batfastad wrote:Anyone have any info on this type of syntax?
Where would I find it in the PHP manual?
It's in the description of the string type, http://www.php.net/manual/en/language.t ... ote]String access and modification by character

Characters within strings may be accessed and modified by specifying the zero-based offset of the desired character after the string using square array-brackets like $str[42] so think of a string as an array of characters.

Note: They may also be accessed using braces like $str{42} for the same purpose. However, using square array-brackets is preferred because the {braces} style is deprecated as of PHP 6. [/quote]
User avatar
batfastad
Forum Contributor
Posts: 433
Joined: Tue Mar 30, 2004 4:24 am
Location: London, UK

Post by batfastad »

Awesome, thanks for all the help guys!
Post Reply