DIM3NSION
DIM3NSION

Reputation: 1761

PHP adding a character into variable

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

Answers (7)

mcgrailm
mcgrailm

Reputation: 17640

you want to use str_replace

$var; // from your post $var = str_replace(" ", "+",$var);

Upvotes: 0

pconcepcion
pconcepcion

Reputation: 5641

You can use:

$my_new_string = str_replace(" ", "+", $my_oldstring)

Upvotes: 1

jensgram
jensgram

Reputation: 31508

Simple case: strtr()

$str = strtr($str, ' ', '+');

Generic: urlencode()

$str = urlencode($str);

Unless I'm misunderstanding the question.

Upvotes: 4

Felix Kling
Felix Kling

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

Mike Thomsen
Mike Thomsen

Reputation: 37506

$str = 'Kanye West';
$str = str_replace(' ', '+', $str);

Upvotes: 0

awm
awm

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

65Fbef05
65Fbef05

Reputation: 4522

Try str_replace(' ', '+', $originalString) on the PHP side before output.

Upvotes: 1

Related Questions