PDA

View Full Version : How to prepend a hyphen to uppercase characters in a string



AppsRU
01-09-2013, 12:58 PM
I wondered if there was a short way to place a hyphen before every capital letter in a string except the first capital?

If string is OneTwoThree I need it to read One-Two-Three

Tnx

jscheuer1
01-09-2013, 01:40 PM
There may or may not be a shortcut method, and/or a more efficient way of putting together existing methods, but this works:


<?php
$string = 'OneTwoThree';
$shortstrings = array(substr($string, 0, 1), substr($string, 1));
$shortstrings[1] = preg_replace("/([A-Z])/", "-$1", $shortstrings[1]);
$newstring = implode('', $shortstrings);
echo $newstring;
?>

If you're turning it into a function, you should test to make sure $string is a string and has a strlen of at least 2. Like:


<?php
$mystring = 'OneTwoThree';
function hypenatecaps($string){
if(!is_string($string)){return;}
if(strlen($string) < 2){
return $string;
}
$shortstrings = array(substr($string, 0, 1), substr($string, 1));
$shortstrings[1] = preg_replace("/([A-Z])/", "-$1", $shortstrings[1]);
$newstring = implode('', $shortstrings);
return $newstring;
}
echo hypenatecaps($mystring);
?>

This also works:


<?php
$string = 'OneTwoThree';
echo substr($string, 0, 1) . preg_replace("/([A-Z])/", "-$1", substr($string, 1));
?>

AppsRU
01-09-2013, 02:05 PM
Thanks John!

I'm just splitting file names and also found this works nice.

function splitAtUpperCase($s) {

return preg_replace(/(?<!^)([A-Z])/', '-\\1', $s);
}
echo splitAtUpperCase($s);

jscheuer1
01-09-2013, 02:34 PM
Please don't link to other sites unnecessarily.


return preg_replace(‘/(?<!^)([A-Z])/', '-\\1', $s);

Will not work because of the non-standard quote (red in the above). But it's a good concept. And using a standard quote fixes it:


return preg_replace('/(?<!^)([A-Z])/', '-\\1', $s);