PHP preg_replace三次有三种不同的模式?对还是错?

mat*_*att 10 php regex preg-replace

嘿伙计们,简单的问题......这是最好的方法吗?

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

$content = preg_replace($pattern1, '', $content);
$content = preg_replace($pattern2, '', $content);
$content = preg_replace($pattern3, '', $content);
Run Code Online (Sandbox Code Playgroud)

我想要过滤掉三种搜索模式!我的代码是否合适或有更好的方法吗?

谢谢你的信息

Fel*_*ing 25

当您使用相同的替换时,您可以传递一个数组

$content = preg_replace(array($pattern1,$pattern2, $pattern3), '', $content);
Run Code Online (Sandbox Code Playgroud)

或创建一个表达式:

$content = preg_replace('/regexp1|regexp2|regexp3/', '', $content);
Run Code Online (Sandbox Code Playgroud)

如果"表达式"实际上是纯字符串,请str_replace改用.


小智 7

希望这个例子帮助你理解"在数组中查找"和"从数组中替换"

$pattern=array('1','2','3');
$replace=array('one','two','tree');
$content = preg_replace($pattern,$replace, $content);
Run Code Online (Sandbox Code Playgroud)


pat*_*ick 7

一种非常易读的方法是使用模式和替换来创建一个数组,然后在array_keysarray_values中使用和preg_replace

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

这甚至适用于更复杂的模式。以下代码将替换1、2和3,并将删除双精度空格。

$replace = [
   "1"       => "one",
   "2"       => "two",
   "3"       => "three",
   "/ {2,}/" => " "
];
$content = preg_replace( array_keys( $replace ), array_values( $replace ), $content );
Run Code Online (Sandbox Code Playgroud)