0

我试图用 + 替换字符串中的所有空格,但是在我执行 preg_replace() 之后,我得到一个空白字符串作为结果。

为什么?我究竟做错了什么?

$query = "hello world";
$formattedQuery = preg_replace('\s', '+', $query);
echo "formatted Query is: ".$formattedQuery;
/* output should be hello+world, but I am getting nothing / blank string outputted */
4

4 回答 4

8

为什么不使用str_replace()

$query = "hello world";
$formattedQuery = str_replace(' ', '+', $query);
echo "formatted Query is: ".$formattedQuery;

如果您坚持使用,preg_replace()则将第一个参数转换为正则表达式:

$query = "hello world";
$formattedQuery = preg_replace('/\s+/', '+', $query);
echo "formatted Query is: ".$formattedQuery;
于 2013-06-20T14:36:01.790 回答
4

如果您通过 URL 处理数据,您实际需要的urlencode不是替换空格

$query = "hello world";
echo urlencode($query);

如果不是,那么您可以使用

echo preg_replace('/\s+/', "+", $query);

输出

hello+world
于 2013-06-20T14:37:35.417 回答
1

$formattedQuery = preg_replace('/\s/', '+', $query);

于 2013-06-20T14:52:23.557 回答
1

对于 preg_replace,尝试:

preg_replace('/\s+/', '+', $query);
于 2013-06-20T14:36:54.713 回答