PHP preg_replace three times with three different templates? right or wrong?

Hey guys, a simple question ... Is this the best way to do this?

$pattern1 = "regexp1"; $pattern2 = "regexp2"; $pattern3 = "regexp3"; $content = preg_replace($pattern1, '', $content); $content = preg_replace($pattern2, '', $content); $content = preg_replace($pattern3, '', $content); 

I have three search patterns that I want to filter out! Is my code above suitable or is there a better way?

thanks for the information

+4
source share
4 answers

How do you replace everything with the same thing, you can either pass an array

 $content = preg_replace(array($pattern1,$pattern2, $pattern3), '', $content); 

or create one expression:

 $content = preg_replace('/regexp1|regexp2|regexp3/', '', $content); 

If the "expressions" are actually pure character strings, use str_replace .

+20
source

hope this example helps you understand "find in array" and "replace from array"

 $pattern=array('1','2','3'); $replace=array('one','two','tree'); $content = preg_replace($pattern,$replace, $content); 
+5
source

To execute multiple requests in one call to preg_replace() , use an array of templates. You can still pass one replacement, this is what matches all three patterns, is replaced by:

 $content = preg_replace(array($pattern1, $pattern2, $pattern3), '', $content); 
+4
source

A very readable approach is to create an array with patterns and replacements, and then use array_keys and array_values in preg_replace

 $replace = [ "1" => "one", "2" => "two", "3" => "three" ]; $content = preg_replace( array_keys( $replace ), array_values( $replace ), $content ); 

This even works with more complex patterns. The following code will replace 1, 2, and 3, and it will remove double spaces.

 $replace = [ "1" => "one", "2" => "two", "3" => "three", "/ {2,}/" => " " ]; $content = preg_replace( array_keys( $replace ), array_values( $replace ), $content ); 
+1
source

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


All Articles