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!

2
  • Is the whole string a CSV? Are the values meant to be handled individually? Commented Mar 29, 2013 at 21:41
  • possible duplicate stackoverflow.com/questions/6729710/… Commented Mar 29, 2013 at 21:47

5 Answers 5

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?

Sign up to request clarification or add additional context in comments.

Comments

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

Comments

1

You can try substr_replace

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

Output

SanJose, California

Comments

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

Comments

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

1 Comment

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.