简体   繁体   English

PHP preg_replace 表达式满足以下要求?

[英]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:要求:

  1. Remove Extra space between words.删除单词之间的多余空格。
  2. allow Capital & Small letter & number & dot(.) & single quotes(').允许大写 & 小写字母 & 数字 & 点 (.) & 单引号 (')。
  3. Do Not allow space at starting and ending of string.字符串的开头和结尾不允许有空格。

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.

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