Page 1 of 1

Get first letter after space

Posted: Sun Oct 10, 2010 7:58 pm
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

Re: Get first letter after space

Posted: Sun Oct 10, 2010 9:18 pm
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;

Re: Get first letter after space

Posted: Mon Oct 11, 2010 2:41 pm
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