简体   繁体   English

regexp从字符串中删除空格,但不能在'或“之间

[英]regexp remove white space from string but not between ' or "

How to remove all whitespaces from string but not between single or double qoutes? 如何从字符串中删除所有空格,但不能删除单个或两个qoutes之间的空格?

for example, I have text: 例如,我有文字:

$request = $requests[ $requestsCnt];
var_dump($request );
var_dump( getmypid());

$query = 'SELECT  FROM users';

$query2 = 'SELECT `*` FROM       
   `users`';

die;

$array = [ '    ' => 'bb']

I need to preserve whitespaces in $query and $query2 My regexp is \\s+(?![^'].*') , but in doesn't work with: 我需要在$query$query2保留空格我的正则表达式是\\s+(?![^'].*') ,但是in不适用于:

$query2 = 'SELECT `*` FROM       
`users`';

and

$array = [ '    ' => 'bb']

This regular expression will remove all horizontal whitespace (to preserve new lines) from a string (in this case, it seems to ve a PHP file): 这个正则表达式将从字符串中删除所有水平空白(以保留新行)(在这种情况下,它似乎是一个PHP文件):

\h+(?=([^']*'[^']*')*[^']*$)

**Details**

\h                     # Any whitespace except new lines, one or more times
(?=                    # Positive lookahead
([^']*'[^']*')*[^']*$  # Match anything in between single quotes
)

PHP example 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

Demo 演示版

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM