0

How do I add - in between strings. Let’s say for instance, I want to add - in 123456789101 at the fourth position three times thereby making it look like this : 1234-5678-9101.

Substr_replace() or str_replace has not solved the problem.

bigpreshy
  • 31
  • 6

2 Answers2

4

I would use combination of str_split and implode.

$code = 123456789101;
$formatted = implode('-', str_split($code, 4) );
echo $formatted; //1234-5678-9101
Stefmachine
  • 382
  • 4
  • 11
1

There are a number of ways to do this.

Use substr

$output = sprintf('%s-%s-%s', substr($string, 0,4), substr($string,4,4), substr(8,4));

Use preg_replace

$output = preg_replace('/(.{4,4})(.{4,4})(.{4,4})/', '$1-$2-$3', $string);
ryantxr
  • 4,119
  • 1
  • 11
  • 25