2015-04-02 55 views
0

哪個php函數可以用來從字符串中提取大寫的單詞?如何從文本中提取大寫的部分?

例如,我有:

... a large text that contains CAPITALIZED PARTS ...

,我需要以編程方式從中提取CAPITALIZED PARTS

我已經搜索了互聯網,但還沒有找到任何解決方案。

+0

使用reguler表達 – 2015-04-02 11:27:20

+0

@Testing,我的問題的確是重複的。在問這個問題之前我搜索了堆棧溢出,我怎麼錯過了這個問題。 – qwaz 2015-04-02 11:40:22

+0

沒問題。 :)他們都給了你類似的答案,就像那個問題中的回答一樣。 :) – 2015-04-02 11:41:56

回答

1

可以使用\\b[A-Z]+\\b正則表達式來獲得ALLCAPS單詞,preg_match_all

這裏是一個sample program

<?php 
$re = "/\\b[A-Z]+\\b/"; 
$str = "a large text that contains CAPITALIZED PARTS"; 
preg_match_all($re, $str, $matches); 
foreach ($matches as $val) { 
    print_r($val); 
} 
?> 

輸出:

Array                                                             
(                                                              
    [0] => CAPITALIZED                                                         
    [1] => PARTS                                                          
)  
+0

OP只請求'CAPITALIZED PARTS'不以'CAPITAL AND SMALL'開頭。你應該考慮發佈一些'演示鏈接'。 – 2015-04-02 11:31:03

+0

我看,帖子已更新。 「大寫」與ALLCAPS的單詞不一樣。 – 2015-04-02 11:33:41

+0

是的,你是對的。請考慮更新您的答案,因爲它似乎是我的好回答。 – 2015-04-02 11:34:39

1
preg_match_all('/\b([A-Z]+)\b/', $str, $matches); 
0
$re = "/[A-Z]*/"; 
$str = "a large text that contains CAPITALIZED PARTS"; 
preg_match_all($re, $str, $matches); 


$newArr = array(); 
foreach($matches[0] as $mat){ 
    if(strlen($mat)>0) 
    $newArr[] = $mat; 
} 
print_r($newArr);