$string = "MaryGoesToSchool";
$expectedoutput = "Mary Goes To School";
views:
158answers:
3
+5
A:
Try this:
$expectedoutput = preg_replace('/(\p{Ll})(\p{Lu})/u', '\1 \2', $string);
The \p{…}
notations are describing characters via Unicode character properties; \p{Ll}
denotes a lowercase letter and \p{Lu}
an uppercase letter.
Another approach would be this:
$expectedoutput = preg_replace('/\p{Lu}(?<=\p{L}\p{Lu})/u', ' \0', $string);
Here every uppercase letter is only prepended with a space if it’s preceded by another letter. So MaryHasACat
will also work.
Gumbo
2010-01-10 10:47:04
+5
A:
What about something like this :
$string = "MaryGoesToSchool";
$spaced = preg_replace('/([A-Z])/', ' $1', $string);
var_dump($spaced);
This :
- Matches the uppercase letters
- And replace each one of them by a space, and what was matched
Which gives this output :
string ' Mary Goes To School' (length=20)
And you can then use :
$trimmed = trim($spaced);
var_dump($trimmed);
To remove the space at the beginning, which gets you :
string 'Mary Goes To School' (length=19)
Pascal MARTIN
2010-01-10 10:47:43
What if the string already has leading whitespace?
Gumbo
2010-01-10 10:56:04
Then `preg_replace('/ *([A-Z])/', ' $1', $string);`.
KennyTM
2010-01-10 12:20:20
A:
Here is a non-regex solution which i use to format a camelCase string to a more readable format:
<?php
function formatCamelCase( $string ) {
$output = "";
foreach( str_split( $string ) as $char ) {
strtoupper( $char ) == $char and $output and $output .= " ";
$output .= $char;
}
return $output;
}
echo formatCamelCase("MaryGoesToSchool"); // Mary Goes To School
echo formatCamelCase("MaryHasACat"); // Mary Has A Cat
?>
alexn
2010-01-10 10:59:49