skip to Main Content

I would need to change the format to 123.456.789.11, so far I have only managed to do it as shown in the example https://regex101.com/r/sY1nH4/1, but I would need it to always have 3 digits at the beginning, thank you for your help

$repl = preg_replace('/(?!^)(?=(?:d{3})+$)/m', '.', $input);

4

Answers


  1. I would use this approach, using a capture group:

    $input = "12345678911";
    $output = preg_replace("/(d{3})(?=d)/", "$1.", $input);
    echo $output;  // 123.456.789.11
    

    The above replaces every 3 numbers, starting from the left, with the same numbers followed by a dot, provided that at least one other digit follows.

    Login or Signup to reply.
  2. You should assert that it is not the end of the string instead to prevent adding a dot at the end:

    d{3}(?!$)K
    
    • d{3} Match 3 digits
    • (?!$) Negative lookahead, assert not the end of the string to the right
    • K Forget what is matched so far

    Regex demo

    $re = '/d{3}(?!$)K/m';
    $str = '111222333444
    11222333444';
    
    $result = preg_replace($re, ".", $str);
    
    echo $result;
    

    Output

    111.222.333.444
    112.223.334.44
    
    Login or Signup to reply.
  3. Here is a possible solution using B (opposite of b):

    d{3}BK
    

    Replace it with .

    RegEx Demo

    By using B after 3 digits we ensure that we don’t match the last position.

    Login or Signup to reply.
  4. No need for a regular expression actually. split into equal parts, join with comma:

    $formatted = implode(',', str_split($str, 3));
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search