简体   繁体   中英

PHP to SEARCH the Upper+Lower Case mixed Words in the strings?

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 (AZ az)
    (eg: No numbers, NO commas, NO full-stops, NO dash .. etc)

So suppose, when i search (for eg 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?

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]); 

Ω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);
?>

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM