Reputation: 1761
I have a form that when submitted loads in the post id into a variable. However some of the options in the form have spaces between the words. For example
one option is "Kanye West" now it loads into the variable the words Kanye and West with a space inbetween.
I need to be able to add a + symbol between these two words instead of a space. So it would be Kanye+West. How would i go about doing this?
Upvotes: 1
Views: 1733
Reputation: 17640
you want to use str_replace
$var; // from your post $var = str_replace(" ", "+",$var);
Upvotes: 0
Reputation: 5641
You can use:
$my_new_string = str_replace(" ", "+", $my_oldstring)
Upvotes: 1
Reputation: 31508
Simple case: strtr()
$str = strtr($str, ' ', '+');
Generic: urlencode()
$str = urlencode($str);
Unless I'm misunderstanding the question.
Upvotes: 4
Reputation: 816242
You can use strtr()
:
$str = strtr(trim($str), ' ', '+');
If you want to replace several consecutive white space characters with one +
, use preg_replace
:
$str = preg_replace('/\s+/','+', trim($str));
Upvotes: 2
Reputation: 6570
The urlencode function was designed exactly for this purpose. It converts all special characters (including space) to their url-safe equivalents (e.g. +
).
Upvotes: 3
Reputation: 4522
Try str_replace(' ', '+', $originalString)
on the PHP side before output.
Upvotes: 1