如何使用 preg_replace PHP 用特殊字符替换一段文本

How to replace a block of text with special characters using preg_replace PHP

我正在使用以下内容:

$pattern_array = array();
$replace_array = array();
$pattern_array[] = '#\[vc_row][vc_column width="1/2" css=".vc_custom_1503896034143{margin-bottom: 40px !important;}"][shortcode_testimonials_carousel#i';
$replace_array[] = '[vc_row fixed_width="true"][vc_column width="1/2" css=".vc_custom_1503896034143{margin-bottom: 40px !important;}"][shortcode_testimonials_carousel';
echo preg_replace($pattern_array, $replace_array, $content);

要替换此文本:

[vc_row][vc_column width="1/2" css=".vc_custom_1503896034143{margin-bottom: 40px !important;}"][shortcode_testimonials_carousel

加上这段文字:

[vc_row fixed_width="true"][vc_column width="1/2" css=".vc_custom_1503896034143{margin-bottom: 40px !important;}"][shortcode_testimonials_carousel

但我收到错误:

preg_replace(): Compilation failed: range out of order in character class at offset 69

我不需要任何正则表达式规则或任何东西,我只想用另一个忽略所有 [方括号] 和 "quotemarks" 替换一个文本块,有什么方法可以用 preg_replace?

附带说明一下,我知道我可以使用 str_replace,但我将其添加到循环遍历数组并已使用 preg_replace 的函数中,因此 str_replace不是一个选项。

您只需要转义正则表达式中使用的特殊字符。有一个很棒的函数叫做 preg_quote,它会自动完成。

$pattern_array = array();
$replace_array = array();
$pattern_array[] = '#' . preg_quote('[vc_row][vc_column width="1/2" css=".vc_custom_1503896034143{margin-bottom: 40px !important;}"][shortcode_testimonials_carousel', '#') . '#i';
$replace_array[] = '[vc_row fixed_width="true"][vc_column width="1/2" css=".vc_custom_1503896034143{margin-bottom: 40px !important;}"][shortcode_testimonials_carousel';
echo preg_replace($pattern_array, $replace_array, $content);