Auto-escape apostrophe/quotes?

In a Wordpress function, I use a random quote - in which I manually escape apostrophes and single-quotes.

Example:

<?php // Random quote
$quoteList = array(
'It\'s simple',
);
echo $quoteList[mt_rand(0, count($quoteList)-1)];
?>

Can they be auto-escaped, and if so… how?

If you use double quotes you don’t have to escape single quotes and vice versa.

So your example could be written as

<?php // Random quote
$quoteList = array(
"It's simple",
);
echo $quoteList[mt_rand(0, count($quoteList)-1)];
?>

Also I suggest you have a look at the array_rand function.

@rpkamp …Thanks. I wasn’t aware of the single/double quote thing.

Being a tad OCD, I try not to use double quotes unless necessary - my eyesight is worsening, and I’ve at times mistaken two single quotes for a double, etcetera.

And, thanks for the advice on array_rand - I’ve looked, and will return to it later when I’ve a clearer head.

What you could also do is just create a very large string and then split it by lines

<?php // Random quote
$quotes = <<<QUOTES
It's simple
It's a wonderful life
This is "wonderful"
I don't know
QUOTES;
$quoteList = explode("\n", $quotes);
echo $quoteList[array_rand($quoteList)];
?>

So long as you insert text beween <<<QUOTES and QUOTES you can use both double quotes and single quotes without having to escape anything.

@rpkamp … Again - thanks. That’s genuinely useful stuff which’ll make my life easier.

1 Like

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.