Search code examples
phpregexcamelcasing

Converting all underscore connected letters to uppercase in php


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.


Solution

  • 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], "_"));
    }