Works for a Living
Works for a Living

Reputation: 1293

Passing multiple backslashes in function argument not working

This

echo date('g:iA \o\n D, M jS', strtotime('2018-02-23 07:42:22'));

echoes this

7:42AM on Fri, Feb 23rd

but this

function dateformat($source, $format = "Y-m-d")
{
    if(empty($source) || $source == '0000-00-00') return false;
    $date = date($format, strtotime($source));
    if(date('Y', strtotime($date)) == '1969' && strpos($source, '1969') === false) return false;
    if(date('Y', strtotime($date)) == '1970' && strpos($source, '1970') === false) return false;
    return $date;
}
echo dateformat('2018-02-23 07:42:22', 'g:iA \o\n D, M jS');

echoes this

While this

echo dateformat('2018-02-23 07:42:22', "g:iA \o\n D, M jS");

echoes this

7:42AM o Fri, Feb 23rd

In other words, with single quotes, I get a return value of false. With double quotes, the function argument passes the \o correctly, but not the \n.

All sorts of different tests yield unpredictable results. I thought it had to do with \n being reserved, so I tried \o\o just to test. That returned false, while \o\n passed the \o successfully.

I've been using this function for years this way, and just now noticed the issue, so I thought perhaps it might have to do with my recent switch from Dreamweaver to Visual Studio Code, but I took these tests over to PHP Sandbox and got the same results, so it's not a code editor issue.

If there's not a solution (which would be my first preference), is there at least an explanation as to what is causing this behavior?

UPDATE: To sum up the major problem, I can't pass more than one backslashed character to the function's argument. It will return false if I do. But anything I want to do works fine in the native php date function.

Upvotes: 0

Views: 94

Answers (1)

AbraCadaver
AbraCadaver

Reputation: 78994

For the single-quoted string the escaped characters are literal \o\n and this, returns false, so does your function:

$date = date($format, strtotime($source));

For the double quoted string the characters are escaped, however \n is the escape sequence for a newline and so you get a newline not n. Do a view source on the page and you will see:

7:42AM o
 Fri, Feb 23rd

To correct this use a double escape:

"g:iA \o\\n D, M jS"

Upvotes: 2

Related Questions