我需要从字符串中删除所有空格,但引号应该保持原样。
这是一个例子:
string to parse:
hola hola "pepsi cola" yay
output:
holahola"pepsi cola"yay
任何的想法?我确信这可以用正则表达式完成,但任何解决方案都可以。
我需要从字符串中删除所有空格,但引号应该保持原样。
这是一个例子:
string to parse:
hola hola "pepsi cola" yay
output:
holahola"pepsi cola"yay
任何的想法?我确信这可以用正则表达式完成,但任何解决方案都可以。
我们可以匹配字符串或引号
[^\s"]+|"[^"]*"
所以我们只需要连接preg_match_all
并连接结果。
示例:
$str = 'hola hola "pepsi cola" yay';
preg_match_all('/[^\s"]+|"[^"]*"/', $str, $matches);
echo implode('', $matches[0]);
// holahola"pepsi cola"yay
Martti,重新提出了这个问题,因为它有一个简单的解决方案,可以让您一次性完成替换 - 无需内爆。(在对有关如何在 regex 中排除模式的一般问题进行一些研究时发现了您的问题。)
这是我们的简单正则表达式:
"[^"]*"(*SKIP)(*F)|\s+
The left side of the alternation matches complete "quoted strings"
then deliberately fails. The right side matches whitespace characters, and we know they are the right whitespace characters because they were not matched by the expression on the left.
This code shows how to use the regex (see the results at the bottom of the online demo):
<?php
$regex = '~"[^"]*"(*SKIP)(*F)|\s+~';
$subject = 'hola hola "pepsi cola" yay';
$replaced = preg_replace($regex,"",$subject);
echo $replaced."<br />\n";
?>
Reference
How to match (or replace) a pattern except in situations s1, s2, s3...