Remove spaces in string, excluding these in specified between specified characters

☆樱花仙子☆ 提交于 2019-12-13 10:51:27

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!