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

后端 未结 5 1811
北海茫月
北海茫月 2020-12-30 07:43

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

$pattern1 = \"regexp1\";
$pattern2 = \"regexp2\";
$pattern3 = \"regexp3\";

$content = preg_replace($patter         


        
5条回答
  •  太阳男子
    2020-12-30 08:23

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

提交回复
热议问题