简体   繁体   中英

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). 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.

use str_replace() function

$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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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