Regex - Remove single whitespace

两盒软妹~` 提交于 2021-01-28 07:18:54

问题


I´ve got a string that looks like this:

"T E S T  R E N T A L  A K T I E B O L A G"

And I want it to look like this:

"TEST RENTAL AKTIEBOLAG"

But I can´t seem to find the right regex expression for my problem. I would like to remove one single whitespace between each character.

Kind Regards / H


回答1:


You can use the regex:

\s(\s)?

And replace with $1.

regex101 demo




回答2:


An alternative solution to @Jerry's answer:

preg_replace('# (?! )#','',$text)

regex101 demo

3v4l.org demo




回答3:


you couldnt use str_replace(' ', '', $your_string); because it will return "TESTRENTALAKTIEBOLAG" and not "TEST RENTAL AKTIEBOLAG"

But you can use bellow code:

$my_string = "T E S T  R E N T A L  A K T I E B O L A G";
$string_a = str_replace('  ','+',$my_string);
$string_b = str_replace(' ','',$string_a );
$final_string = str_replace('+',' ',$string_b);

echo $final_string;

3v4l.org




回答4:


str_replace(' ', '', $your_string);


来源:https://stackoverflow.com/questions/19788171/regex-remove-single-whitespace

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!