Search code examples
phpstringdigits

Modify a 4 digit number inside of a string and inserting colon


I have a string and i want to modify all 4 digit numbers and inserting colon between. Example: 1320 will become 13:20

$data = "The time is 1020 and the time is 1340 and 1550";

I'm thinking to use preg_match('/[0-9]{4}/', '????', $data);

But not sure how to pass the same value again in the preg?


Solution

  • One way could be to use preg_replace instead and use capturing groups to capture 2 times 2 digits (\d{2})(\d{2}) between word boundaries \b

    In the replacement use the 2 capturing groups using $1:$2

    $data = "The time is 1020 and the time is 1340 and 1550";
    $data = preg_replace('/\b(\d{2})(\d{2})\b/', "$1:$2", $data);
    echo $data;
    

    Result:

    The time is 10:20 and the time is 13:40 and 15:50
    

    Php demo