问题
I have a string:
Some string, "it's a nice string". I like it. "some other text"
I want remove spaces, excluding there beetween ":
Somestring,"it's a nice string".Ilikeit."some other text"
How I can goal this?
回答1:
You could use regular expressions, or you could cheat and use explode()
:
$text_before = 'Some string, "it\'s a nice string". I like it. "some other text"';
$text_after = array();
$text_quotes = explode('"', $text_before);
for ($i = 0, $max = count($text_quotes); $i < $max; $i++) {
if (($i % 2) == 1) {
$text_after[] = $text_quotes[$i];
} else {
$text_after[] = str_replace(' ', '', $text_quotes[$i]);
}
}
echo implode('"', $text_after);
回答2:
You may achieve it by using php str_replace function. Please check http://php.net/manual/en/function.str-replace.php
回答3:
I'm not good with regex, so this solution doesn't use any. What I would do:
$str = 'Some string, "it\'s a nice string". I like it. "some other text"';
$pieces = explode('"', $str);
for($i = 0; $i < count($pieces); $i += 2){ // Every other chunk is quoted
$pieces[$i] = str_replace(' ', '', $pieces[$i]);
}
$str = implode('"', $pieces);
If the string starts with double quotes, php will make the first element of the $pieces
array empty, so this should still work.
来源:https://stackoverflow.com/questions/8589361/remove-spaces-in-string-excluding-these-in-specified-between-specified-characte