问题
Lets say there is a string like:
A quick brOwn FOX called F. 4lviN
The WORDS i want TO SEARCH must have the following conditions:
- The words containing MIXED Upper & Lower Cases
- Containing ONLY alphabets A to Z (A-Z a-z)
(e.g: No numbers, NO commas, NO full-stops, NO dash .. etc)
So suppose, when i search (for e.g in this string), the search result will be:
brOwn
Because it is the only word which contains both of Upper & Lower Case letters inside (and also containing only alphabets).
So how can I make it work in php?
回答1:
You should be good with:
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]);
Edit: As capturing is not needed, it can be also >>
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]);
回答2:
Ωmega's answer works just fine. Just for fun, here's an alternate (commented) regex that does the trick using lookahead:
<?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);
?>
回答3:
You could use a simple regular expression, such as:
/\s[A-Z][a-z]+\s/
That could be used like so:
preg_match_all('/\s[A-Z][a-z]+\s/', 'A quick Brown FOX called F. 4lvin', $arr);
Then your $arr variable which has had all the matches added to it, will contain an array of those words:
Array
(
[0] => Array
(
[0] => Brown
)
)
Edit: Changed the pattern.
来源:https://stackoverflow.com/questions/11593880/php-to-search-the-upperlower-case-mixed-words-in-the-strings