preg_replace 不在引号内的字符串

preg_replace a string that's not inside quotes

我有这个字符串:

$str = "<script> alert( 'Alert 1' ); alert( 'Alert 2' ); </script>";

我正在执行 preg_replace 删除字符串中的空格:

$str = preg_replace('% %', '', $str);

但我不确定如何修改正则表达式(如果可能的话!)以告诉它忽略单引号内的任何空格。

尝试使用这个正则表达式,

[ ](?=([^\"']*[\"'][^\"']*[\"'])*[^\"']*$)