简体   繁体   English

尝试用字符串中的+替换所有空格

[英]Trying to replace all spaces with + in string

I'm trying to replace all spaces with +'s in a string, but after I do the preg_replace(), I get a blank string as the result. 我试图用字符串中的+替换所有空格,但是在执行preg_replace()之后,得到的结果为空字符串。

Why? 为什么? What am I doing wrong? 我究竟做错了什么?

$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 */

Why not use str_replace() 为什么不使用str_replace()

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

If your insist on using preg_replace() then turn the first parameter into a regular expression: 如果您坚持使用preg_replace()则将第一个参数转换为正则表达式:

$query = "hello world";
$formattedQuery = preg_replace('/\s+/', '+', $query);
echo "formatted Query is: ".$formattedQuery;

If you are working with data over URL what you actually need is urlencode not replace spaces 如果您正在通过URL处理数据,那么实际需要的是urlencode而不是空格

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

If Not then you can use 如果不是,那么您可以使用

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

Output 输出量

hello+world

对于preg_replace,请尝试:

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

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

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

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