[英]PHP to SEARCH the Upper+Lower Case mixed Words in the strings?
可以說有一個像這樣的字符串:
A quick brOwn FOX called F. 4lviN
我要搜索的單詞必須具有以下條件:
因此,假設當我搜索(例如在此字符串中)時,搜索結果將是:
brOwn
因為它是唯一一個同時包含大寫和小寫字母的單詞(並且也僅包含字母)。
那么如何使它在php中工作呢?
您應該擅長:
preg_match_all("/\b([a-z]+[A-Z]+[a-zA-Z]*|[A-Z]+[a-z]+[a-zA-Z]*)\b/", $input, $matches);
print_r($matches[1]);
編輯:由於不需要捕獲,它也可以>>
preg_match_all("/\b(?:[a-z]+[A-Z]+[a-zA-Z]*|[A-Z]+[a-z]+[a-zA-Z]*)\b/", $input, $matches);
print_r($matches[0]);
Ωmega的答案很好。 只是為了好玩,這里有一個備用的(經注釋的)正則表達式,可以使用超前功能來解決問題:
<?php // test.php Rev:20120721_1400
$re = '/# Match word having both upper and lowercase letters.
\b # Assert word begins on word boundary.
(?=[A-Z]*[a-z]) # Assert word has at least one lowercase.
(?=[a-z]*[A-Z]) # Assert word has at least one uppercase.
[A-Za-z]+ # Match word with both upper and lowercase.
\b # Assert word ends on word boundary.
/x';
$text ='A quick brOwn FOX called F. 4lviN';
preg_match_all($re, $text, $matches);
$results = $matches[0];
print_r($results);
?>
您可以使用簡單的正則表達式,例如:
/\s[A-Z][a-z]+\s/
可以這樣使用:
preg_match_all('/\s[A-Z][a-z]+\s/', 'A quick Brown FOX called F. 4lvin', $arr);
然后,已將所有匹配項添加到其中的$ arr變量將包含這些單詞的數組:
Array
(
[0] => Array
(
[0] => Brown
)
)
編輯:更改了模式。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.