Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

A simple question: Is this the best way to do it?

$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 I want to filter out! Is my code above appropriate or is there a better way?

like image 674
matt Avatar asked Feb 19 '11 17:02

matt


2 Answers

As you are replacing all with the same, you could do 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 instead.

like image 97
Felix Kling Avatar answered Oct 04 '22 19:10

Felix Kling


A very readable approach is to make an array with patterns and replacements, and then use array_keys and array_values in the 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 );
like image 36
patrick Avatar answered Oct 04 '22 20:10

patrick