Home  >  Article  >  Backend Development  >  使用正则表达式s来匹配空格,总是会少匹配一个空格

使用正则表达式s来匹配空格,总是会少匹配一个空格

WBOY
WBOYOriginal
2016-06-23 13:47:471133browse

	$abc = "TC,           M1";	$abc = ereg_replace(",[\s]+", ",", $abc);	echo $abc;


以上代码是想删除字符串str中逗号以后的空格,期待结果是“TC,M1”
但实际运行的结果却是"TC, M1",在逗号和M1之间多个一个空格,是为什么呢


回复讨论(解决方案)

	$abc = 'TC,           M1';	$abc = preg_replace("/,[\s]+/", ",", $abc);	echo "<br>$abc";


试了下,使用preg_replace,结果是正确的,没有那个空格了,这是为什么呢

ereg 函数组已在废止之列,没必要纠结了

$abc = "TC,           M1";$a=str_replace(' ','',$abc);echo $a;

TC,M1

再说 ereg 也没有 \s 这样的表述

建议你用preg_replace , 这个函数要更快。

一定要用ereg_replace , 可以改为:
$abc = ereg_replace(",[ ]+", ",", $abc);

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn