Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

php single and double quotes

Tags:

php

//remove line breaks
function safeEmail($string) {
     return  preg_replace( '((?:\n|\r|\t|%0A|%0D|%08|%09)+)i' , '', $string );
}

/*** example usage 1***/
$from = 'HTML Email\r\t\n';

/*** example usage 2***/
$from = "HTML Email\r\t\n";

if(strlen($from) < 100)
{
    $from = safeEmail($from);

    echo $from;
}

1 returns HTML Email\r\t\n while 2 returns HTML Email

what's with the quotes?

like image 725
Frank Nwoko Avatar asked Jan 03 '11 11:01

Frank Nwoko


2 Answers

As per the PHP Documentation

Unlike the double-quoted and heredoc syntaxes, variables and escape sequences for special characters will not be expanded when they occur in single quoted strings.

In other words, double quoted strings expand variables and escape sequences for special characters. Single quoted strings don't.

So in example1, with the single quoted string, the string is exactly as you see it. Slashes and all.

But in example2, rather than ending with the string \r\t\n, it ends with a carriage return, a tab and then a new line. In other words the escape sequences for special characters are expanded.

like image 148
Yacoby Avatar answered Oct 06 '22 00:10

Yacoby


with single quotes in PHP those special characters as \n \r \t... doesn't work as expected. According to the docs:

To specify a literal single quote, escape it with a backslash (\). To specify a literal backslash, double it (\\). All other instances of backslash will be treated as a literal backslash: this means that the other escape sequences you might be used to, such as \r or \n, will be output literally as specified rather than having any special meaning.

like image 36
maid450 Avatar answered Oct 05 '22 23:10

maid450