How to avoid issue with single quotes while using it in the PHP code?

Hi Support,

We have a PHP code with an array like this:

array(
        'title' => 'Dewalist Classifieds',
        'image' => '/files/network/dewalist_classifieds_image.jpg',
...

In the title if we have a single quote within the title, how do we avoid that to crash?

Thank you,
Dewalist

5 Likes

@dladmin

To avoid issues with single quotes within the title while using it in your PHP code, you can escape the single quote character using a backslash. This way, PHP will treat the single quote as a literal character and not as the end of the string.

Here’s an example:

$array = array(
    'title' => 'Dewalist\'s Classifieds', // Using backslash to escape the single quote
    'image' => '/files/network/dewalist_classifieds_image.jpg'
);

In the above code, the title value is set to “Dewalist’s Classifieds” with the single quote properly escaped.

Alternatively, if you’re generating the array dynamically and want to handle any special characters automatically, you can use the addslashes() function to escape the single quotes.

Here’s an example:

$title = "Dewalist's Classifieds";
$array = array(
    'title' => addslashes($title), // Using addslashes() to automatically escape special characters
    'image' => '/files/network/dewalist_classifieds_image.jpg'
);

In this case, the addslashes() function will escape any special characters in the title, including single quotes, and store the escaped string in the array.

I hope this helps.

3 Likes