在PHP中的链接中,空格被'+'替换

I have a value in variable as follows...

$variable = "chicken soup.jpg";

when i do the following, spaces are converted to a + symbol in the output

$body = "www.abc.com/" . $variable
mail($to, $subject, $body,$headers)

Output in mail received: www.abc.com/chicken+soup.jpg

But i want the output as below ? Please help

Expected Output : www.abc.com/chicken%20soup.jpg or www.abc.com/chicken soup.jpg

i tried using str_replace function but no luck

I'm pretty sure, if your email-client supports to view the plain source of that message, you'll se that the url is "www.abc.com/chicken soup.jpg"; only your browser / email client encodes it, as it's an invalid URL.

If you want to produce a valid url, encode it manually with:

$body = 'www.abc.com/' . urlencode( $variable );
// this will be 'www.abc.com/chicken+soup.jpg' as this is a valid url

or:

$body = 'www.abc.com/' . rawurlencode( $variable );
// this will be 'www.abc.com/chicken%20soup.jpg'

Edit:

You can read more about the difference:

This is because all urls are encoded. It may be your E-Mail client recieves 'chicken soup.jpg' but parses it as an url and so it gets 'chicken+soup.jpg' as ' ' in urls are not valid.

Your solution is to use urlencode() on the filename variable. This will convert spaces and other non-URL-friendly characters into %20 et al so that it can be used as part of a valid URL.

Example:

$variable = urlencode("chicken soup.jpg"); echo $variable;

Output:

chicken%20soup.jpg

Check the the urlencode() documentation for more information.