Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Escape quote or special characters in array value

In my PHP code, I'm setting up an area for people to enter their own info to be displayed. The info is stored in an array and I want to make it as flexible as possible.

If I have something like...

$myArray[]['Text'] = 'Don't want this to fail';

or

$myArray[]['Text'] = "This has to be "easy" to do";

How would I go about escaping the apostrophe or quote within the array value?

Thanks

Edit: Since there is only a one to one relationship, I changed my array to this structure...

$linksArray['Link Name'] ='/path/to/link';
$linksArray['Link Name2'] ='/path/to/link2';
$linksArray['Link Name2'] ='/path/to/link3';

The plan is I set up a template with an include file that has these links in a format someone else (a less technical person) can maintain. They will have direct access to the PHP and I'm afraid they may put a single or double quote in the "link name" area and break the system.

Thanks again.

POSSIBLE SOLUTION:

Thanks @Tim Cooper.

Here's a sample that worked for me...

$link = "http://www.google.com";
$text = <<<TEXT
Don't you loving "googling" things
TEXT;
$linksArray[$text] = $link;
like image 637
Don Avatar asked Dec 02 '25 03:12

Don


2 Answers

Using a heredoc might be a good solution:

$myArray[]['Text'] = <<<TEXT

Place text here without escaping " or '

TEXT;

PHP will process these strings properly upon input. If you are constructing the strings yourself as you have shown, you can alternate between quotation styles (single and double)...as in:

$myArray[]['Text'] = "Don't want this to fail";
$myArray[]['Text'] = 'This has to be "easy" to do';

Or, if you must escape the characters, you use the \ character before the quotation.

$myArray[]['Text'] = 'Don\'t want this to fail';
$myArray[]['Text'] = "This has to be \"easy\" to do";
like image 39
Jordan Arseno Avatar answered Dec 03 '25 17:12

Jordan Arseno