note 87102 deleted from function.preg-replace by crell

From: Date: Fri, 01 Jul 2022 19:37:09 +0000
Subject: note 87102 deleted from function.preg-replace by crell
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-218841@lists.php.net to get a copy of this message
Note Submitter: jette at nerdgirl dot dk ---- I use this to prevent users from overdoing repeated text. The following function only allows 3 identical characters at a time and also takes care of repetitions with whitespace added. This means that 'haaaaaaleluuuujaaaaa' becomes 'haaaleluuujaaa' and 'I am c o o o o o o l' becomes 'I am c o o o l' <?php //Example of user input $str = "aaaaaaaaaaabbccccccccaaaaad d d d d d d ddde''''''''''''"; function stripRepeat($str) { //Do not allow repeated whitespace $str = preg_replace("/(\s){2,}/",'$1',$str); //Result: aaaaaaaaaaabbccccccccaaaaad d d d d d d ddde'''''''''''' //Do not allow more than 3 identical characters separated by any whitespace $str = preg_replace('{( ?.)\1{4,}}','$1$1$1',$str); //Final result: aaabbcccaaad d d ddde''' return $str; } ?> To prevent any repetitions of characters, you only need this: <?php $str = preg_replace('{(.)\1+}','$1',$str); //Result: abcad d d d d d d de' ?>

« previous php.notes (#218841) next »