Francesco Francesco - 10 months ago 73
PHP Question

PHP: add hyphen anytime a string contains a number after one letter or more

In my DB i have items names that can be input by users either in the form of Apple MM1 or Banana B-234 or Carl Mm345 (I can't really control too much what users input)

I'd like to be able to convert

Carl Mm345
and convert it in
Carl MM-345
by using PHP: basically adding a dash or hyphen and uppercase all the letter before dash

function convert_input($string) {
    $arr = explode(' ', $string);
    if (count($arr) == 1) {
        $first = '';
        $second = strtoupper($string);
    } else {
        $first = $arr[0].' ';
        $second = strtoupper($arr[1]);
    $second = str_replace('-', '', $second);
    $p = strcspn($second, '0123456789');
    $letters = substr($second, 0, $p);
    $numbers = substr($second, $p);
    $glue = $letters && $numbers ? '-' : '';
    return $first.$letters.$glue.$numbers;

echo convert_input('mm234');
echo convert_input('Carl Mm345');
echo convert_input('adsf mmmm');
echo convert_input('adsf');
echo convert_input('adsfdsf 123');
echo convert_input('Banana B-234');