Search code examples
phpreplace

Mask a string with dashes in PHP


I have the following string:

$thetextstring = "jjfnj 948"

At the end I want to have:

echo $thetextstring; // should print jjf-nj948

So basically what I am trying to do is to remove the spaces from the string then separate the first 3 letters from the rest of the string with a -.

So far I have

$string = trim(preg_replace('/s+/', ' ', $thetextstring));

$result =  explode(" ", $thetextstring);

$newstring = implode('', $result);

print_r($newstring);

I have been able to join the words, but how do I add the separator after the first 3 letters?


Solution

  • Oldschool without regex

    $test = "jjfnj 948";
    $test = str_replace(" ", "", $test);  // strip all spaces from string
    echo substr($test, 0, 3)."-".substr($test, 3);  // isolate first three chars, add hyphen, and concat all characters after the first three