-1

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;'";
cpcdev
  • 1,130
  • 3
  • 18
  • 45
  • 1
    _"the output results in"_ - what is the code in between? How do you echo/vardump `$output`? And you would have a single-quote problem in js anyway: `style='background:url('https..` the second `'` would need to be escaped. But it all depends on how you output it to where. – Jeff Jun 06 '19 at 18:59
  • its echoed at the end "echo $output;" – cpcdev Jun 06 '19 at 19:00
  • 1
    there must be something in between, because also the single quote here `style='back` changes to a double quote. See this fiddle: https://3v4l.org/b9e4C The code you are showing here is working as you'd expect. – Jeff Jun 06 '19 at 19:02
  • Just the 2 lines at the top of your question produce the correct output. – Dave Jun 06 '19 at 19:09

1 Answers1

3

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.

Don't Panic
  • 41,125
  • 10
  • 61
  • 80