简体   繁体   中英

php - How do I extract capitalised words from a string

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

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.

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.

$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);

here is some code:

$arr = explode($words, ' ');

for ($word as $words){
    if($word[0] == strtoupper($word[0]){
        $newarr[] = $word;

print join(', ', $newarr);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM