Get first letter after space

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
Quazel
Forum Commoner
Posts: 25
Joined: Thu Mar 18, 2010 7:12 pm
Location: Edina, Minnesota

Get first letter after space

Post by Quazel »

Is there a php script that will parse a line of text and return only the first letter after the spaces something like

Code: Select all

$text = "the cat climbed the tree with sharp claws"
for_each(' ') {
$text = find(' '+1);
}
echo $text;
The Output:

Code: Select all

tccttwsc
User avatar
Weirdan
Moderator
Posts: 5978
Joined: Mon Nov 03, 2003 6:13 pm
Location: Odessa, Ukraine

Re: Get first letter after space

Post by Weirdan »

Code: Select all

$text = "the cat climbed the tree with sharp claws";
preg_match_all('/\b(\w)/', $text, $matches);
$letters = '';
foreach ($matches[1] as $letter) {
   $letters .= $letter;
}
echo $letters;
User avatar
McInfo
DevNet Resident
Posts: 1532
Joined: Wed Apr 01, 2009 1:31 pm

Re: Get first letter after space

Post by McInfo »

Here is a non-regex solution.

Compact version:

Code: Select all

<?php
function getFirstLettersOfWords ($sentence) {
    $firstLetters = '';
    $offset = -1;
    do {
        $firstLetters .= substr($sentence, ++$offset, 1);
    } while (($offset = strpos($sentence, ' ', $offset)) !== false);

    return $firstLetters;
}
$text = 'the cat climbed the tree with sharp claws';
echo getFirstLettersOfWords($text); // tccttwsc
Expanded version:

Code: Select all

<?php
function getFirstLettersOfWords ($sentence, $delimiter = ' ', $letterLength = 1) {
    $firstLetters = '';
    $offset = -$letterLength;
    do {
        $offset = $offset + $letterLength;
        $firstLetters = $firstLetters . substr($sentence, $offset, $letterLength);
        $offset = strpos($sentence, $delimiter, $offset);
    } while ($offset !== false);

    return $firstLetters;
}
$text = 'the cat climbed the tree with sharp claws';
echo getFirstLettersOfWords($text); // tccttwsc
Post Reply