note 87102 added to function.preg-replace

From: Date: Wed, 19 Nov 2008 12:47:41 +0000
Subject: note 87102 added to function.preg-replace
Groups: php.notes 
Request: Send a blank email to php-notes+get-146707@lists.php.net to get a copy of this message
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' ?> ---- Server IP: 87.54.44.10 Probable Submitter: 80.167.136.250 ---- Manual Page -- http://www.php.net/manual/en/function.preg-replace.php Edit -- https://master.php.net/note/edit/87102 Del: integrated -- https://master.php.net/note/delete/87102/integrated Del: useless -- https://master.php.net/note/delete/87102/useless Del: bad code -- https://master.php.net/note/delete/87102/bad+code Del: spam -- https://master.php.net/note/delete/87102/spam Del: non-english -- https://master.php.net/note/delete/87102/non-english Del: in docs -- https://master.php.net/note/delete/87102/in+docs Del: other reasons-- https://master.php.net/note/delete/87102 Reject -- https://master.php.net/note/reject/87102 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#146707) next »