Oscar
Oscar

Reputation: 1103

How to get all first character in sentences using PHP?

What I want to do is only get all the first character in the sentences, I knew substr can do this, but my substr only able to get one character.

I use this code now, but it is only get H instead of HW

substr($string,0,1);

what I want is

$string = "Hello World";
$result = "HW";

Any idea how to do this ?

Thanks

Upvotes: 0

Views: 1080

Answers (6)

Robin
Robin

Reputation: 1216

This would be a solution without regex:

$yourString = "This is a test";
$yourArray = explode(" ",$yourString);
$firstLetters = "";
foreach($yourArray as $word) {
    $firstLetters .= strtoupper($word[0]);
}

echo $firstLetters; // > TIAT

Upvotes: 0

WizKid
WizKid

Reputation: 4908

$string = 'Hello, World!';
$result = '';
foreach (preg_split('#[^a-z]+#i', $string, -1, PREG_SPLIT_NO_EMPTY) as $word) {
    $result .= $word[0];
}
var_dump($result);

Demo: https://eval.in/158045

Upvotes: 2

Fabricator
Fabricator

Reputation: 12782

yet another regex solution:

$s = "hello world, it's me";                                                                                                                                                                                   
preg_match_all('/\b\w/', $s, $matches);                                                                                                                                                                        
echo implode('', $matches[0]);

prints hwism

Upvotes: 0

xdazz
xdazz

Reputation: 160943

You could use regex:

$string = "Hello World";
preg_match_all('/^.|(?<=\s)./', $string, $matches);
var_dump($matches);

Upvotes: 0

StackSlave
StackSlave

Reputation: 10617

Try this:

function string_from_first_letter_of_each_word($string){
  $sA = explode(' ', $string); $r = '';
  foreach($sA as $v){
    $r .= substr($v, 0, 1);
  }
  return $r;
}
echo string_from_first_letter_of_each_word('Hello World');

Upvotes: 0

BrandonMXB
BrandonMXB

Reputation: 89

You could easily make a loop that would check if current index of char is capital (using the ctype_upper($char) function). If it's capital, add it to an array or print it out.

Upvotes: 0

Related Questions