[英]PHP preg_replace expression for following requirement?
Input text:输入文本:
Hello, raj's dogs age is 18. "
Output:输出:
Hello, raj's dogs age is 18.
Requirements:要求:
Replace multiples spaces with one space.用一个空格替换多个空格。
echo trim(preg_replace('/\h+/', ' ', ' Hello, raj\'s dogs age is 18. '));
The \\h
is a horizontal whitespace (tab/space). \\h
是水平空白(制表符/空格)。 The +
after means at least one must be preset.后面的+
表示必须至少预设一个。 The space in the replacement replaces the one or more with just one.替换中的空格仅用一个替换一个或多个。 PHP's trim
can then be used to remove leading/trailing spaces.然后可以使用 PHP 的trim
来删除前导/尾随空格。
use str_replace() function使用 str_replace() 函数
$string = " Hello, raj's dogs age is 18. ";
$result=str_replace(' ', ' ', $string);
echo $result;
Try replacing two or more whitespace characters with just a single space:尝试用一个空格替换两个或多个空格字符:
$string = " Hello, raj's dogs age is 18. ";
$result = trim(preg_replace('/\s{2,}/', ' ', $string));
echo $result;
This prints:这打印:
Hello, raj's dogs age is 18.
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.