Take this string:
Israel agrees to significant easing of Gaza blockade
I want to return the capitalised words, separated by a comma, like this:
Israel,Gaza
I imagine it must be possible. Any ideas?
Take this string:
Israel agrees to significant easing of Gaza blockade
I want to return the capitalised words, separated by a comma, like this:
Israel,Gaza
I imagine it must be possible. Any ideas?
Split the string into it's words with explode(' '), iterate through the words and check if the word is capitalized by checking if it's first letter ($str[0]
) is the same as its uppercase variant (strtoupper($str[0])
). You can fill an array with the results and then join(',') it
A simple way would be to use this regular expression to filter out the capitalized words, and then joining the matches array into a string:
preg_match_all('/[A-Z][a-z]+/', 'Israel agrees to significant easing of Gaza blockade', $matches);
echo implode(',' $matches[0]);
(Answer restored since I guess it isn't really wrong per se...)
here is some code:
$arr = explode($words, ' ');
for ($word as $words){
if($word[0] == strtoupper($word[0]){
$newarr[] = $word;
print join(', ', $newarr);
You can use a regular expression. Something like the following should get your close:
<?php
$str = 'Israel agrees to significant easing of Gaza blockade';
preg_match_all('/([A-Z]{1}\w+)[^\w]*/', $str, $matches);
print_r($matches);
?>
Edit: My regex was way off.
Code as suggested by @Patrick Daryll Glandien.
$stringArray = explode(" ", $string);
foreach($stringArray as $word){
if($word[0]==strtoupper($word[0])){
$capitalizedWords[] = $word;
}
}
$capitalizedWords = join(",",$capitalizedWords);
//$capitalizedWords = implode(",",$capitalizedWords);
Use preg_match_all()
:
preg_match_all('/[A-Z]+[\w]*/', $str, $matches);
If you need to work with non-English or accent characters, then use:
preg_match_all('/\p{L}*\p{Lu}+\p{L}*/', $str, $matches);
Which should also work for words where the first letter isn't capitalized, but a subsequent letter is as is customary in some languages/words.
$str = 'Israel agrees to significant easing of Gaza blockade';
$result = array();
$tok = strtok($str, ' ');
do {
if($tok == ucfirst($tok))
$result[] = $tok;
}
while(($tok = strtok(' ')) !== false);