14

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?

0

4 Answers 4

30

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.

Sign up to request clarification or add additional context in comments.

Comments

12

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 );

3 Comments

I like how you did it. However, depending on how simple the pattern is, you can aways shorhand the code: $content = preg_replace(["1", "2", " 3" ], ["one", "two", "three"], $content);
It’s about readability. The replace array can be much easier read than using two separate arrays. Try an array with more elements, and then edit the 125th or so. This is why I use the replace array and array_keys/array_values. Remember: you (or someone else) might have to reading your code at a later stage...
I agree with you, entirely, which is the primary reason why I specifically said "depending on how simple the pattern is...". The code quality sometimes can be improved by short-hand statements, which is a sharp tool. As such, as a double bladed knife, it can be dangerous too. Use it wisely.
8

hope this example helping you to understand "find in array", and "replace from array"

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

Comments

4

To do multiple searches in a single preg_replace() call, use an array of patterns. You can still pass a single replacement, this is what's matched by all three patterns is replaced with:

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.