Preg_replace和可能的json问题


preg_replace and possible json issues

我需要替换任何换行符开头的空白。我使用JSON发送POST值,并怀疑这可能与它不工作有关。

$str='
This is a string.
   This should be left justified by removing whitespaces preceding it.
';
preg_replace('/^'s+/', '', $str);

运行这个,按预期工作。当我尝试将它与POST数组一起使用时,空格仍然存在。为什么?

JSON在其中起作用吗?

编辑:

只是为了澄清,被发送过来的数组不是JSON编码,它是使用JSON POST的PHP数组。

我只是试着修改我的正则表达式一点,至少可以验证preg_replace正在做一些的事情。如果我选择:/'s+/,所有空格都被删除。所以,我知道它在某种程度上起作用了。

我的正则表达式正确吗?

编辑# 2

这让我发疯了。我想我会在我的javascript中修剪空白并称之为一天,但我得到了相同的结果。

是否有其他情况会阻止这个正则表达式匹配?

/^'s+/

这个呢:

$str='
This is a string.
   This should be left justified by removing whitespaces preceding it.
';
preg_replace('/^'s+/m', '', $str);

我刚刚添加了m修饰符。见http://us3.php.net/manual/en/reference.pcre.pattern.modifiers.php

try this:

foreach($trim_val as $key => $value) {
    $trim_val[$key] = trim($value);
}
$json = json_encode($trim_val);

已经有人给出了解决方案,检查