删除字符串中的空格,排除指定字符之间指定的空格

发布于 2024-12-22 07:28:22 字数 231 浏览 3 评论 0原文

我有一个字符串:

Some string, "it's a nice string". I like it. "some other text"

我想删除空格,不包括“:

Somestring,"it's a nice string".Ilikeit."some other text"

我如何才能实现这个目标?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

花辞树 2024-12-29 07:28:22

您可以使用正则表达式,也可以作弊并使用 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);

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);
水晶透心 2024-12-29 07:28:22

您可以使用 php str_replace 函数来实现它。请检查 http://php.net/manual/en/function.str-replace .php

You may achieve it by using php str_replace function. Please check http://php.net/manual/en/function.str-replace.php

红尘作伴 2024-12-29 07:28:22

我不擅长正则表达式,所以这个解决方案不使用任何正则表达式。我会做什么:

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

如果字符串以双引号开头,php 将使 $pieces 数组的第一个元素为空,所以这应该仍然有效。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文