哪個php函數可以用來從字符串中提取大寫的單詞?如何從文本中提取大寫的部分?
例如,我有:
... a large text that contains CAPITALIZED PARTS ...
,我需要以編程方式從中提取CAPITALIZED PARTS
。
我已經搜索了互聯網,但還沒有找到任何解決方案。
哪個php函數可以用來從字符串中提取大寫的單詞?如何從文本中提取大寫的部分?
例如,我有:
... a large text that contains CAPITALIZED PARTS ...
,我需要以編程方式從中提取CAPITALIZED PARTS
。
我已經搜索了互聯網,但還沒有找到任何解決方案。
可以使用\\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
)
OP只請求'CAPITALIZED PARTS'不以'CAPITAL AND SMALL'開頭。你應該考慮發佈一些'演示鏈接'。 – 2015-04-02 11:31:03
我看,帖子已更新。 「大寫」與ALLCAPS的單詞不一樣。 – 2015-04-02 11:33:41
是的,你是對的。請考慮更新您的答案,因爲它似乎是我的好回答。 – 2015-04-02 11:34:39
preg_match_all('/\b([A-Z]+)\b/', $str, $matches);
我會用正則表達式這區分大小寫
$string='... a large text that contains CAPITALIZED PARTS ...'
preg_match_all('%[A-Z]+%', $string, $matches);
var_dump($matches);
$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);
使用reguler表達 – 2015-04-02 11:27:20
@Testing,我的問題的確是重複的。在問這個問題之前我搜索了堆棧溢出,我怎麼錯過了這個問題。 – qwaz 2015-04-02 11:40:22
沒問題。 :)他們都給了你類似的答案,就像那個問題中的回答一樣。 :) – 2015-04-02 11:41:56