Match duplicate spaces with preg_replace

I am writing a WordPress plugin, and one of the functions is to remove duplicate spaces.

My code is as follows:

return preg_replace('/\s\s+/u', ' ', $text, -1, $count);
  • I don’t understand why I need a u modifier. I saw other plugins that use preg_replaceand do not use, you need to change it for Unicode. I believe that I have the default installation of WordPress.

  • Without a modifier, the code replaces all spaces with Unicode instead of glyphs instead of replacement.

  • With a modifier, uI don't get glyphs, and it doesn't replace all spaces.

Each space below has 1-10 spaces. The regular expression is removed only in space from each group.

Before:

This sentence  has extra space.  This doesn’t.  Extra  space, Lots          of extra space.

After:

This sentence has extra space. This doesn’t. Extra space, Lots         of extra space.

$count= 9

How to get a regular expression to replace an entire match with one space?


: php,
$new_text = preg_replace('/\s\s+/', ' ', $text, -1, $count);

, wordpress. :

function jje_test( $text ) {
    $new_text = preg_replace('/\s\s+/', ' ', $text, -1, $count);
    echo "Count: $count";
    return $new_text;
}

add_filter('the_content', 'jje_test');

:

  • the_content
    remove_all_filters('the_content');
  • , the_content,
  • \s+, \s\s+, [ ]+ ..
  • ,
+3
5

, / :

return preg_replace('/[\p{Z}\s]{2,}/u', ' ', $text);

/u, $text , UTF-8. , PCRE $text.

\p{Z} , PCRE ASCII , \s, /u. \p{Z} Unicode-. , .

, echo WordPress - .

+6

u UTF-8, , - 0x7f. UTF-8 , .

, 0x7f. . , , , unicode\uA0 .

, "" Unicode. , ... script ?

+2

jjeaton , , / . , . , .. ( ) ..

return preg_replace('/([\p{Z}\s])[\p{Z}\s]+/u', '$1', $text);

, , . , ( ) .

+2
source

I don't know any modifiers, but it did the trick:

<?php
$text = ' Hi,   my name is    Andrés.  ';
echo preg_replace(array('/^\s+/', '/\s+$/', '/\s{2,}/'), ' ', $text);
/*
Hi, my name is Andrés.
*/
?>
0
source
preg_replace('!\s+!', ' ', 'This sentence  has extra space.  This doesn’t.  Extra  space, Lots          of extra space.');
0
source

Source: https://habr.com/ru/post/1752187/


All Articles