Replace one symbol with another in PHP

1

I'm trying to replace all the signals from + to vírgula with PHP. I'm doing it this way:

$q = $_GET['q'];
$string = str_replace("+",",","$q");

This is removing the sign from + , but it returns an empty space instead of the comma. If anyone can tell me what I'm doing wrong.

    
asked by anonymous 19.11.2017 / 02:06

1 answer

0

What should happen is that + represents space, so when using $_GET['q'] it contains space, not the + symbol. This internal PHP exchange causes str_replace to not work because there is no + at that point.

For your code to work you should replace + with %2B , so if you have:

https://site.com/q=1+2+3

Switch to:

https://site.com/q=1%2B2%2B3

Your code will work, because %2B is the hexadecimal code for + , in ASCII, it will not be converted to space by PHP.

To convert automatically you can use http_build_query , which follows RFC3986 if specified:

echo 'https://site.com?' . http_build_query(['q' => '1+2+3'], '', '&', PHP_QUERY_RFC3986);

For example. This will result in the URL mentioned above, which will work.

    
29.11.2017 / 04:44