Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP DateTime::format with html character entities

I'm writing dates to the DOM from a MySQL database that are being formatted by PHP's DateTime class (my server's running PHP 5.5.14) like this

$start_date->format('M. d, Y');

However, the year is wrapping to a new line when it reaches the end of the div. I wish I could insert a non-breaking space like this:

$start_date->format('M. d, Y');

But the class thinks think the n and s are format characters, and spits out this gibberish: Mar.&3b30p;27,&3b30p;2015

Could I escape those characters? Or would I have to make a function that replaces the spaces with html character entities after the date has been formatted?

like image 442
kas Avatar asked Jun 17 '26 14:06

kas


2 Answers

You need to escape the ones that are format characters:

'M.&\n\b\s\p;d,&\n\b\s\p;Y'

I just escaped them all instead of looking up which ones were necessary to be escaped. It's also easier to see that they are not meant as a part of the format if they are escaped.

This is only going to work in the single-quoted string as \n will be a newline in double-quoted.

like image 131
AbraCadaver Avatar answered Jun 20 '26 04:06

AbraCadaver


You can prevent this by escaping n and s with a preceding backslash.

This line of code should work for you:

$start_date->format('M.&\nb\sp;d,&\nb\sp;Y');

This will output: Mar. 27, 2015

A nice example of date formatting: http://php.net/manual/en/function.date.php#example-2501

like image 42
Companjo Avatar answered Jun 20 '26 05:06

Companjo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!