Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find and replace Date/Time within Text and make it Bold

Tags:

regex

php

I have searched Stackoverflow for some answers to this and have tried numerous ways to make this work without success. So I was hoping some genius out there would be able to help me.

I am retrieving text from a database that has within it dates/times (dd/mm/yy hh:mm:ss) within that text I would like to bold all instances where the regex finds a date in this format.

For example:

09/09/2013 16:42:01 Australia/West (Fake Name):

09/09/2013 15:44:01 (alert) alert stage 2

09/09/2013 15:38:55 Australia/West (Fake Name): 2 of the at Store have come back online.

09/09/2013 15:33:17 Australia/West (Fake Name): Store is having issues with their all 3. loading". Investigating.

09/09/2013 15:30:02 Australia/West (Fake Name):

would look something like this:

09/09/2013 16:42:01 Australia/West (Fake Name):

09/09/2013 15:44:01 (alert) alert stage 2

09/09/2013 15:38:55 Australia/West (Fake Name): 2 of the at Store have come back online.

09/09/2013 15:33:17 Australia/West (Fake Name): Store is having issues with their all 3. loading". Investigating.

09/09/2013 15:30:02 Australia/West (Fake Name):

I have used this regex for the date/time:

preg_match_all('/^\d{2}\/\d{2}\/\d{4} \d{2}:\d{2}:\d{2}/',$text,$matches);

with this code:

foreach ($matches as $res) 
{
    $replaceStr = "<strong>" . $res . "</strong>";
    str_replace($res, $replaceStr, $text);
}

but it seems to only find 1 match in the text so I need a little bit of help.

like image 455
Andrew Burns Avatar asked Dec 03 '25 03:12

Andrew Burns


1 Answers

No need for a foreach loop:

preg_replace('/^\d{2}\/\d{2}\/\d{4} \d{2}:\d{2}:\d{2}/m','<strong>$0</strong>', $text);

does all the matching and replacing at once.

like image 166
Tim Pietzcker Avatar answered Dec 04 '25 19:12

Tim Pietzcker