如何从字符串中删除所有空格,而不是在单个或双重qoutes之间删除?
例如,我有文字:
$request = $requests[ $requestsCnt];
var_dump($request );
var_dump( getmypid());
$query = 'SELECT FROM users';
$query2 = 'SELECT `*` FROM
`users`';
die;
$array = [ ' ' => 'bb']
我需要保留$query
和$query2
中的空格
我的正则表达式为\s+(?![^'].*')
,但不适用于:
$query2 = 'SELECT `*` FROM
`users`';
和
$array = [ ' ' => 'bb']
答案 0 :(得分:0)
这个正则表达式将从字符串中删除所有水平空格(以保留新行)(在这种情况下,它似乎是一个PHP文件):
\h+(?=([^']*'[^']*')*[^']*$)
**Details**
\h # Any whitespace except new lines, one or more times
(?= # Positive lookahead
([^']*'[^']*')*[^']*$ # Match anything in between single quotes
)
PHP示例
<pre>
<?php
$s = '
$request = $requests[ $requestsCnt];
var_dump($request );
var_dump( getmypid());
$query = \'SELECT FROM users\';
$query2 = \'SELECT `*` FROM
`users`\';
die;
$array = [ \' \' => \'bb\']';
$s = preg_replace("/\h+(?=([^']*'[^']*')*[^']*$)/i", "", $s);
echo nl2br($s); // <pre> and nl2br() to show formatted code