Convert Dashes to CamelCase in PHP

前端 未结 25 1193
南笙
南笙 2020-12-07 19:40

Can someone help me complete this PHP function? I want to take a string like this: \'this-is-a-string\' and convert it to this: \'thisIsAString\':

function d         


        
相关标签:
25条回答
  • 2020-12-07 20:17

    $stringWithDash = 'Pending-Seller-Confirmation'; $camelize = str_replace('-', '', ucwords($stringWithDash, '-')); echo $camelize; output: PendingSellerConfirmation

    ucwords second(optional) parameter helps in identify a separator to camelize the string. str_replace is used to finalize the output by removing the separator.

    0 讨论(0)
  • 2020-12-07 20:19

    Here is a small helper function using a functional array_reduce approach. Requires at least PHP 7.0

    private function toCamelCase(string $stringToTransform, string $delimiter = '_'): string
    {
        return array_reduce(
            explode($delimiter, $stringToTransform),
            function ($carry, string $part): string {
                return $carry === null ? $part: $carry . ucfirst($part);
            }
        );
    }
    
    0 讨论(0)
  • I would probably use preg_replace_callback(), like this:

    function dashesToCamelCase($string, $capitalizeFirstCharacter = false) {
      return preg_replace_callback("/-[a-zA-Z]/", 'removeDashAndCapitalize', $string);
    }
    
    function removeDashAndCapitalize($matches) {
      return strtoupper($matches[0][1]);
    }
    
    0 讨论(0)
  • 2020-12-07 20:23
    function camelCase($text) {
        return array_reduce(
             explode('-', strtolower($text)),
             function ($carry, $value) {
                 $carry .= ucfirst($value);
                 return $carry;
             },
             '');
    }
    

    Obviously, if another delimiter than '-', e.g. '_', is to be matched too, then this won't work, then a preg_replace could convert all (consecutive) delimiters to '-' in $text first...

    0 讨论(0)
  • 2020-12-07 20:24

    This is simpler :

    $string = preg_replace( '/-(.?)/e',"strtoupper('$1')", strtolower( $string ) );
    
    0 讨论(0)
  • 2020-12-07 20:26

    One liner, PHP >= 5.3:

    $camelCase = lcfirst(join(array_map('ucfirst', explode('-', $url))));
    
    0 讨论(0)
提交回复
热议问题