开发者

PHP adding a character into variable

开发者 https://www.devze.com 2023-03-02 03:22 出处:网络
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

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);

0

精彩评论

暂无评论...
验证码 换一张
取 消