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 wor开发者_开发百科ds. 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?
Simple case: strtr()
$str = strtr($str, ' ', '+');
Generic: urlencode()
$str = urlencode($str);
Unless I'm misunderstanding the question.
The urlencode function was designed exactly for this purpose. It converts all special characters (including space) to their url-safe equivalents (e.g. +
).
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));
Try str_replace(' ', '+', $originalString)
on the PHP side before output.
You can use:
$my_new_string = str_replace(" ", "+", $my_oldstring)
$str = 'Kanye West';
$str = str_replace(' ', '+', $str);
you want to use str_replace
$var; // from your post $var = str_replace(" ", "+",$var);
精彩评论