Replace one symbol with another in PHP

Asked

Viewed 550 times

2

I’m looking to replace all the signs of + for vírgula with PHP. I’m doing it this way:

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

This is removing the signal from +, but it gives me an empty space instead of a comma. If anyone can tell me what I’m doing wrong.

  • and the content of q comes from where?

1 answer

1

What must occur is that the + represents space, so when using the $_GET['q'] it contains space, not the symbol of +. This exchange, internal PHP, makes the str_replace does not work, because there is no + at that point.

For your code to work you must replace the + for %2B, then if you have:

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

Switch to:

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

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


To convert automatically you can use the http_build_query, following 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.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.