Removing extra spaces from within quotes of a string in PHP

Posted by on April 30, 2012 in PHP, Programming | 0 comments

Every once in a while, you may be building strings that include quoted material. The issue is that if you’re doing it programmatically, you may be doing something that quotes different parts of the string. The issue is, that if the field you’re pulling from doesn’t exist, you may leave yourself with extra spaces in your strings. See the example below.

Table: A
Columns: color,number,price,shape
Row1: red,4,3.25,square
Row2: blue,,3.99,round
Row3: ,50,,
Row4: ,,50,

Now if you combined these rows with quotes around everything, and hyphens as delimiters, you’d wind up with the following 3 strings. Note that the delimiter is arbitrary, you can use a replace with any character.
“red-4-3.25-square”
“blue–3.99-round”
“-50–”
“–50-”

Notice that if you trimmed row 3 and row 4, you’d wind up with the same string, but if you left the delimiters in there untouched, you’d have unique strings. For this example we want to talk about the case where you want to combine them both. So how do you get them all out of there?

The first step is to use a simple replace to replace any spot where the delimiters fall next to each other. This will take cause of row 2 where the missing data was in the middle.

$string = str_replace(“–“, “-“, $string);

The simple replace doesn’t help with the edges that are next to the quotes though. You want the quotes next to the first word, not the first delimiter. Therefore, I created the following script to remove the quotes. If you have issues with it, please let me know and I’ll see about improving it to take care of your case. You could modify this to take a dynamic delimiter, or even a dynamic quoting character.

function cleanInsideQuotes($str, $forward=true)
{
if(!$forward){$str = strrev($str);} // reverse it so the same logic can be applied to the end of quotes.

$open = false;
$justOpen = false;
$tempLen = strlen($str);
$newString = “”;

for($x=0;$x<$tempLen;$x++)
{
$tempChar = $str{$x};

if($tempChar=='"')
{
if($open)
{
$open = false;
}
else
{
$open = true;
$justOpen = true;
}
$newString .= $tempChar;
}
elseif($tempChar==" ")
{
if(!$justOpen)
{
$newString .= $tempChar;
}
}
else
{
$justOpen = false;
$newString .= $tempChar;
}
}

$str = $newString;

if($forward) // process it in reverse to catch the spaces before the ending quote.
{
$str = cleanInsideQuotes($str,false);
}
else
{
$str = strrev($str);
}
return $str;
}

If you enjoyed this post, please consider leaving a comment or subscribing to the RSS feed to have future articles delivered to your feed reader.

Leave a Comment

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>