PHP Preg-Replace more than one underscore

How do I use preg_replace to replace more than one underline with just one underline?

+4
source share
8 answers

preg_replace('/[_]+/', '_', $your_string);

+7
source

The + operator matches multiple instances of the last character (or capture group).

 $string = preg_replace('/_+/', '_', $string); 
+17
source

In fact, using /__+/ or /_{2,}/ will be better than /_+/ , since a single underline does not need to be replaced. This will improve the speed of the preg option.

+6
source

Running tests, I found this:

 while (strpos($str, '__') !== false) { $str = str_replace('__', '_', $str); } 

will be consistently faster than this:

 $str = preg_replace('/[_]+/', '_', $str); 

I generated test strings of various lengths as follows:

 $chars = array_merge(array_fill(0, 50, '_'), range('a', 'z')); $str = ''; for ($i = 0; $i < $len; $i++) { // $len varied from 10 to 1000000 $str .= $chars[array_rand($chars)]; } file_put_contents('test_str.txt', $str); 

and tested with these scripts (runs separately, but in the same lines for each value of $ len):

 $str = file_get_contents('test_str.txt'); $start = microtime(true); $str = preg_replace('/[_]+/', '_', $str); echo microtime(true) - $start; 

and

 $str = file_get_contents('test_str.txt'); $start = microtime(true); while (strpos($str, '__') !== false) { $str = str_replace('__', '_', $str); } echo microtime(true) - $start; 

For shorter lines, the str_replace () method was 25% faster than the preg_replace () method. The longer the string, the smaller the difference, and str_replace () is always faster.

I know that some would prefer one method over another for reasons other than speed, and I would be happy to read comments regarding the results, test method, etc.

+5
source

preg_replace ()

need operator +

 $text = "______"; $text = preg_replace('/[_]+/','_',$text); 
+1
source

I have no reason why you want to use preg_replace, but what is wrong:

 str_replace('__', '_', $string); 
0
source
 This will Accept Only Characters,numeric value or Special Character found it will replace with _ <?php error_reporting(0); if($_REQUEST) { PRINT_R("<PRE>"); PRINT_R($_REQUEST); $str=$_REQUEST[str]; $str=preg_replace('/[^A-Za-z\-]/', '_', $str); echo strtolower(preg_replace('/_{2,}/','_',$str)); } ?> <form action="" method="post"> <input type="text" name="str"/> <input type="submit" value="submit"/> </form> 
0
source

You can also use the T-Regx library, which has automatic delimiters.

 pattern('_+')->replace($your_string)->with('_'); 
0
source

All Articles