简体   繁体   中英

Split words between UPPER CASE and lower case

If anyone could help me this would be awesome!

I have this:

TYLLON kevin -convert-> familyname: TYLLON ; prename: kevin

VAN AZERTY bert -convert-> familyname: VAN AZERTY ; prename: bert

YAHOO BE AWESOME rabbit -convert-> familyname: YAHOO BE AWESOME ; prename: rabbit

Maybe regex, anyone?

I believe shortest possible answer is by using preg_split here using look-arounds:

Use this regex for splitting:

/(?<=\p{Lu})\h+(?=\p{Ll})/u

Which matches 1 or more horizontal space that is preceded by a uppercase unicode letter and followed by a lowercase unicode letter.

PS: This solution is unicode compatible.

Examples:

print_r(preg_split('/(?<=\p{Lu})\h+(?=\p{Ll})/u', 'YAHOO BE AWESOME rabbit'));
Array
(
    [0] => YAHOO BE AWESOME
    [1] => rabbit
)

print_r(preg_split('/(?<=\p{Lu})\h+(?=\p{Ll})/u', 'VAN AZERTY bert'));
Array
(
    [0] => VAN AZERTY
    [1] => bert
)

print_r(preg_split('/(?<=\p{Lu})\h+(?=\p{Ll})/u', 'TYLLON kevin'));
Array
(
    [0] => TYLLON
    [1] => kevin
)

You could loop through your name strings using the php function ctype_upper :

Checks if all of the characters in the provided string, text, are uppercase characters.

You would first have to explode() your names and put them in an array. Once you have them in an array you can check for upper case / lower case…

<?php
$name_array = array('VAN', 'AZERTY', 'bert');
foreach ($name_array as $testcase) {
    if (ctype_upper($testcase)) {
        echo "The string $testcase is upper case.";
    } else {
        echo "The string $testcase is lower case / mixed case.";
    }
}
?>

Try this solution.

<?php
   preg_match_all('/\b([A-Z]+)\b/', $fullname, $upper);
   preg_match_all('/\b([a-z]+)\b/', $fullname, $lower);
   $familyname = implode(' ', $upper[0]);
   $prename = implode(' ', $lower[0]);
   echo $prename.' '.$familyname;
?>

I found the answer in combination of multiple answers:

preg_match_all('/\b([A-Z]+)\b/', 'BLA BOEM BABA Kevin', $matches);

RESULT: BLA BOEM BABA

preg_replace('/\b([A-Z]+)\b/', '', 'VAN MELKEBEKE BLA BOEM BABA Kevin');

RESULT: Kevin

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