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.