0

I am currently using preg_match to insert a colon after the second character of a four-character string (1000). I think it is an elegant solution. But I wonder if there are any other elegant solutions for this? Thanks for your ideas!

Working code

$string = '1000';
$r = preg_replace('/^.*(\d{2})(\d{2})$/', '$1:$2', $string);
print_r($r);

// output "10:00"
Maik Lowrey
  • 15,957
  • 6
  • 40
  • 79
  • @DengSihan Thank you! These are two elegant possibilities. I think that is too more a answear as a comment! it's too good to be just a comment. – Maik Lowrey Dec 11 '21 at 15:01
  • @CedricIpkiss Merci for link but i would say more no than yes! For example, the implode method, which is very good, has not yet been listed there. – Maik Lowrey Dec 11 '21 at 15:06

1 Answers1

1

Since you know the position, then it's faster to use substr:

$n   = 2;
$str = substr($str, 0, $n) . ':' . substr($str, $n);

Or you can use substr_replace to the same effect.

$str = substr_replace($str, ':', $n, 0);

If this is a time (i.e. hours and minutes), you can extract the components in case you need them (in some cases, it's clearer, even if less efficient).

$mm  = $str % 100; // Note that this is a number: 8, not 08.
$hh  = ($str - $mm) / 100;

$str2 = sprintf('%02d:%02d', $hh, $mm);
LSerni
  • 55,617
  • 10
  • 65
  • 107