I have a string like "kp_o_zmq_k" and I need to covert it to "kpOZmqK" where I need to convert all letters connected to the right of the underscore(o,z,k in this case) to uppercase.
Asked
Active
Viewed 3,837 times
-4
-
You mean, you want to convert letters that have a preceding underscore to upper-case? – Brad Mar 08 '13 at 04:16
-
Because simply 'connected' would imply that p and q should also be upper-case. – aqua Mar 08 '13 at 04:17
-
What did you come up with? What have you tried? – ultranaut Mar 08 '13 at 04:17
-
What is supposed to happen if you have two underscores in a row? Something like `sadf__ety__hjk` – PriestVallon Mar 08 '13 at 04:19
-
Yes, I want to convert letters preceding underscore to uppercase – Abhiraj Mar 08 '13 at 06:27
2 Answers
7
<?php
function underscore2Camelcase($str) {
// Split string in words.
$words = explode('_', strtolower($str));
$return = '';
foreach ($words as $word) {
$return .= ucfirst(trim($word));
}
return $return;
}
?>

dimirc
- 6,347
- 3
- 23
- 34
2
Try with preg_replace_callback function in php.
$ptn = "/_[a-z]?/";
$str = "kp_o_zmq_k";
$result = preg_replace_callback($ptn,"callbackhandler",$str);
// print the result
echo $result;
function callbackhandler($matches) {
return strtoupper(ltrim($matches[0], "_"));
}

Justin John
- 9,223
- 14
- 70
- 129