
October 10th, 2011, 10:19 AM
|
|
Registered User
|
|
Join Date: Oct 2011
Posts: 3
Time spent in forums: 20 m 55 sec
Reputation Power: 0
|
|
|
Insert space before capitals
I need to put a space before each capital letter, unless there is a capital before it.
// Strings sent
$string = "JobTitle";
$string = "UserGUID";
// Response required
$string = "Job Title";
$string = "User GUID";
Any ideas?
This works in PHP but not as efficient as preg_replace()
PHP Code:
function spacebeforecapital($text) {
// Should be able to achieve this through the magical wizardy of preg_replace()
$chars = str_split($text,1);
$first = true;
$prevchar = " ";
$response="";
foreach($chars as $char) {
if ($first) {
$response = $char;
$first = false;
}
else {
if (preg_match('/[A-Z]$/', $char) && (!(preg_match('/[A-Z]$/', $prevchar)))) {
// Its a capital! and the previous character isn't a capital
$response += " ";
}
$response += $char;
}
$prevchar = $char;
}
return ($response);
}
|