phpregexpreg-matcheregi

String to time - convert eregi_replace to preg_match


Now I'm using function eregi_replace() which is deprecated and I want to convert it to function preg_match(). Now I have this:

foreach ($lesson as $key => $val) {
    $lesson_time[$key]->fromTime = eregi_replace('([0-9]{2})([0-9]{2})', '\1:\2',$val->fromTime);
}

where input ($val->fromTime) is string for example 0830 or 1150 and output is 08:30 or 11:50. I'm not good with regex so I would like to ask how this function with the same process can be convert to preg_match().


Solution

  • preg_match('/([0-9]{2})([0-9]{2})/', $val->fromTime, $match);
    
    print_r($match);
    

    You can't replace string with preg_match. You can use preg_replace.

    preg_replace('/([0-9]{2})([0-9]{2})/', '$1:$2', $val->fromTime);