Search for lowercase then uppercase?
I have a string that is something like
Firstname LastnameFirstname Lastname
and I want to convert t开发者_JS百科hat to
Firstname Lastname, Firstname Lastname
Is there a way in PHP to search for such a character map?
a simple/naiive method:
$string = preg_replace('/([a-z])([A-Z])/', "$1, $2", $string);
but as I put in my comment above, that'll turn Rachel McAdams
into Rachel Mc, Adams
.
<?php
$str = 'Firstname LastnameFirstname Lastname'; // Set our string
$str = preg_replace('/(\w+ \w+[a-z])([A-Z]\w+ \w+)/', '$1, $2', $str); // Find name boundries and insert comman
echo $str; // Firstname Lastname, Firstname Lastname
?>
Detecting uppercase or lowercase isn't so hard. PHP doesn't have a built-in function but you can:
$ord = ord($string[$pos]);
$is_uppercase = $ord <= 90 && $ord >= 65;
Then you could loop over the characters and see which pairs you find, possibly skipping really 'short' pairs, but that's going to be guess work. There is no perfect way to do this as human names have no set format.
A little complicated but work is done
$word = "Firstname LastnameFirstname Lastname";
$word = str_replace('_', ' ', str_replace('_xx', ', ', strtolower(preg_replace('/[^A-Z^a-z^0-9]+/','_',
preg_replace('/([a-z\d])([A-Z])/','\1_xx\2',
preg_replace('/([A-Z]+)([A-Z][a-z])/','\1_\2',$word))))));
echo $word;
first preg_replace searches for strings with the uppercase second searches for strings with uppercase combined with another word first replace helps to replace our _xx to comma plus space second replace replace underscore with the space.
精彩评论