php - 如何从字符串中提取大写单词

时间:2010-06-20 19:04:32

标签: php

取这个字符串:

Israel agrees to significant easing of Gaza blockade

我想返回用逗号分隔的大写单词,如下所示:

Israel,Gaza

我想它一定是可能的。有什么想法吗?

6 个答案:

答案 0 :(得分:9)

将字符串拆分为explode(' ')的单词,迭代单词并检查单词是否大写,检查它的第一个字母($str[0])是否与其大写变体({{ 1}})。您可以使用结果填充数组,然后join(',')

答案 1 :(得分:3)

@Patrick Daryll Glandien建议的代码。

$stringArray = explode(" ", $string);
foreach($stringArray as $word){
  if($word[0]==strtoupper($word[0])){
    $capitalizedWords[] = $word;
  }
}
$capitalizedWords   = join(",",$capitalizedWords);
//$capitalizedWords = implode(",",$capitalizedWords);

答案 2 :(得分:1)

使用preg_match_all()

preg_match_all('/[A-Z]+[\w]*/', $str, $matches);

如果您需要使用非英语或重音字符,请使用:

preg_match_all('/\p{L}*\p{Lu}+\p{L}*/', $str, $matches);

对于第一个字母没有大写字母的单词也适用,但后续字母在某些语言/单词中是惯用的。

答案 3 :(得分:0)

您可以使用正则表达式。如下所示应该让你闭幕:

<?php

$str = 'Israel agrees to significant easing of Gaza blockade';

preg_match_all('/([A-Z]{1}\w+)[^\w]*/', $str, $matches);

print_r($matches);

?>

编辑:我的正则表达式已经过时了。

答案 4 :(得分:0)

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

答案 5 :(得分:-4)

这里有一些代码:

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

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

print join(', ', $newarr);
相关问题