0

I have a php string that outputs like this:

San Jose, California

I need the php string to output like this:

SanJose, Caliornia

I've been playing around with str_replace but not having much luck.

Any help would be appreciated!

fedorqui
  • 275,237
  • 103
  • 548
  • 598

5 Answers5

1

Update: first explode with

$string = explode(",",$string);

then do for all value of $string ( in foreach for example )

For just spaces, use str_replace:

$string = str_replace(' ', '', $string);

For all whitespace, use preg_replace:

$string = preg_replace('/\s+/', '', $string);

look at here How to strip all spaces out of a string in php?

Community
  • 1
  • 1
Ali Akbar Azizi
  • 3,272
  • 3
  • 25
  • 44
1

Maybe it is not very nice, but you can explode and then concatenate:

$your_string="San Jose, California";
$arr = explode(" ", $your_string);
$result = $arr[0] . $arr[1] . " " . $arr[2];
fedorqui
  • 275,237
  • 103
  • 548
  • 598
1

You can try substr_replace

$str = "San Jose, California" ;
echo substr_replace($str, '', strpos($str, " "), 1);

Output

SanJose, California
Baba
  • 94,024
  • 28
  • 166
  • 217
1

Given that the string is a CSV, you could explode it, process each value, and then implode it.

Example:

$string = "San Jose, California";
$values = explode(",", $string);
foreach($values as &$value)
{
    $value = str_replace(" ", "", $value);
}

$output = implode(", ", $values);

*untested

thordarson
  • 5,943
  • 2
  • 17
  • 36
0

Don't use regulars expressions, it is overkill (slower). Use the count parameter of strreplace:

mixed str_replace ( mixed $search , mixed $replace , mixed $subject [, int &$count ] )

From PHP manual:

count

If passed, this will be set to the number of replacements performed.

$str = "San Jose, California";
$result = str_replace(" ", "", $str, 1);
Jean
  • 7,623
  • 6
  • 43
  • 58
  • This is going to produce `Fatal error: Only variables can be passed by reference`. 4th parameter has to be a variable that will be **set** by `str_replace` to number of replacements it performed. – Ejaz Mar 29 '13 at 21:46