Search code examples
phpescapingdouble-quotessingle-quotes

Single Quotes inside Single Quotes removing Forward Slashes


I have this code:

$profile_image_url = str_replace(" ", "%20", 'https://www.example.com/images/cropped (1).jpg');

$output .= "style='background:url('https://www.example.com/images/" . $profile_image_url . "')no-repeat;'";

The output results in:

style="background:url(" https: www.example.com images cropped (1).jpg')no-repeat;

How can I fix this line of code to prevent the URL slashes from being removed? Thank you!

$output .= "style='background:url('https://www.example.com/images/" . $profile_image_url . "')no-repeat;'";

I've tried escaping the innermost single quotes with a backslash but it did not work -->

$output .= "style='background:url(\'https://www.example.com/images/" . $profile_image_url . "\')no-repeat;'";

Solution

  • It's not really removing the slashes. You'll see them if you view the page source rather than using inspect.

    Put the style attribute value in double quotes.

    $output .= "style=\"background:url('https://www.example.com/images/" . $profile_image_url . "')no-repeat;\"";
    

    Or put the URL in double quotes.

    $output .= "style='background:url(\"https://www.example.com/images/" . $profile_image_url . "\")no-repeat;'";
    

    Unescaped single quotes inside single quotes is not possible. The second single quote encountered will close the first one. And escaping them doesn't work in that context, as you've seen.