SaidbakR
SaidbakR

Reputation: 13534

PHP preg_replace datetime and matches

I want to style MySQL datetime format string to be something like the following:

<b>2018-07-09</b><i>10:25:00</i>

I'm trying to use preg_replace() to replace matched patterns like the following:

preg_replace("/([^\s]+)/",\'<b>$1</b><i>$2</i>\',$date)

However, the pattern https://regex101.com/r/LLRx3x/1, indicates that there two matches where each one has one group. The first match is the date, while the second is the time. I could not able to utilize $1 and $2 to access and replace each match. The above preg_match code returns something like:

<b>2018-07-09</b><i></i> <b>13:25:18</b><i></i> So How could I access each match and replace them to get my goal?

Upvotes: 0

Views: 683

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626758

You may capture the date and time into separate 2 groups,then you can use $1 and $2:

preg_replace('~^(\S+)\s+(\S+)$~', '<b>$1</b><i>$2</i>', $date)

See the regex demo and a PHP demo.

Note that the $n replacement backreferences only refer to the corresponding capturing group values, so if you defined one capturing group in your pattern, only 1 capture is accessible with $1 and $2 will hold an empty string, i.e. preg_replace('~^(\S+)\s+\S+$~', '<b>$1</b><i>$2</i>', '2018-07-09 13:25:18') will yield <b>2018-07-09</b><i></i>).

So, the point here is to match both the date and time but capture them into separate capturing groups, and then use the corresponding backreferences accordingly.

Pattern details

  • ^ - start of the string
  • (\S+) - Capturing group 1 (later referred to with $1 backreference): any 1+ non-whitespace chars
  • \s+ - 1+ whitespaces
  • (\S+) - Capturing group 2 (later referred to with $2 backreference): any 1+ non-whitespace chars
  • $ - end of string.

Upvotes: 3

Related Questions