How can I easily add a space between each lowercase and uppercase letter of a string? The trick is that it can only be between lowercase /uppercase, not when you have an uppercase/lowercase.

For example:

camelCase

should become:

camel Case

not:

camel C ase

I've got a solution using preg_match_all and then looping, but there has to be an easier way. Ideas?

    Hmm... what have you tried? This works for me:

    <?php
    
    $strings = array(
    	'camelCase',
    	'camelcase',
    	'sOme worDswhichDon\'tGoTogether'
    );
    
    $pattern = '/(.*?[a-z]{1})([A-Z]{1}.*?)/';
    $replace = '${1} ${2}';
    
    foreach($strings AS $string)
    {
    	echo '<strong>Original:</strong> ', $string,
    		'<br /><strong>Replaced:</strong>', 
    		preg_replace($pattern, $replace, $string),
    		'<br />';
    }
    
    ?>

    Gives this output:

    Original: camelCase
    Replaced:camel Case
    Original: camelcase
    Replaced:camelcase
    Original: sOme worDswhichDon'tGoTogether
    Replaced:s Ome wor Dswhich Don't Go Together

    That's what you want isn't it?

      Considering the original poster hasn't replied, we aren't sure yet :p

        WOOPS. Hehe. Read Drakla's reply and didn't bother to double check the usernames... :o

          Well, you don't need the loop, since preg_replace() can take a whole array of strings and process all of them.
          An alternative pattern might be

          /(?<=[^A-Z])([A-Z])/
          =replace with=> " $1"

            I didn't need a loop, I just needed the regex patterns on how to replace it properly. This works thanks!

              Write a Reply...