2010-06-20 49 views
2

把這個字符串:PHP - 我如何提取大寫單詞從字符串

Israel agrees to significant easing of Gaza blockade 

我想回到大寫單詞,以逗號分隔,就像這樣:

Israel,Gaza 

我想象它一定是可能的。有任何想法嗎?

+0

同樣適用於'加沙同意在以色列緩和導彈襲擊,隧道攻擊和平民恐怖主義'這個句子' – CodyBugstein 2015-02-24 11:52:12

回答

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); 
+0

謝謝你的伎倆。 – Steven 2010-06-20 19:28:10

+0

感謝@Patrick Daryll Glandien。 – Babiker 2010-06-20 19:30:26

+0

或者,你也可以做'ucwords($ word)== $ word'。 – 2010-06-20 19:33:57

9

分割字符串到它的話有explode(' '),通過迭代的話,檢查是否這個詞是通過檢查它的第一個字母($str[0])大寫是一樣的大寫的變種(strtoupper($str[0]))。您可以填寫的結果數組,然後join(',')

+0

不錯。您可能需要添加其他內容來去除大寫字母中的標點符號==>「在法國的國家,讓它變成法國青蛙。」返回「法國,法國」 - 不知道這是從原來的帖子應該發生什麼。此外,可以在爆炸之後切斷前導空格和尾隨空格,以處理單詞之間的多個空格。 – 2010-06-20 21:02:47

-4

這裏是一些代碼:

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

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

print join(', ', $newarr); 
+0

'foreach''''' – 2010-06-20 19:12:13

+1

1.格式不正確2.語法錯誤3.變量命名不一致 – BoltClock 2010-06-20 19:14:12

+0

'$ arr'是應該在循環中使用的數組。你的爆炸參數是倒退的,你在循環中使用了錯誤的變量,根據我以前的評論應該是'foreach'而不是'for'循環。但我可以看到你在做什麼。見上面Babiker的答案。 – 2010-06-20 19:23:09

0

您可以使用正則表達式。類似以下內容應該讓你關閉:

<?php 

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

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

print_r($matches); 

?> 

編輯:我的正則表達式是關閉的。

+0

給我這個錯誤:未知修飾符'W' – Steven 2010-06-20 19:19:58

+0

我的正則表達式是離開的。用我的編輯給它一個去。 – labratmatt 2010-06-20 19:20:51

1

使用preg_match_all()

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

如果您需要非英語或重音字符的工作,然後使用:

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

也應單詞在哪裏工作的第一個字母不是大寫字母,但後續的字母在某些語言/文字中是習慣的。

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); 
相關問題