php str_replace 用正则表达式

php str_replace with regular expression

我有一些文本需要从代码中删除,我使用了很多这样的变体:

$answer = str_replace('<td style="background-color:#80F9CC;">', '', $answer);
$answer = str_replace('<td style="background-color:#E1E3E4;">', '', $answer);
$answer = str_replace('<td style="background-color:#D1D3D4;">', '', $answer);
$answer = str_replace('<td style="background-color:#73F6AB;">', '', $answer);
$answer = str_replace('<td style="background-color:#3CEB88;">', '', $answer);

有没有办法创建一个 str_replace 函数来删除带有某些正则表达式的文本?

preg_replace()就是你需要的功能

假设您想识别和替换颜色的十六进制表示,代码如下:

$answer = preg_replace('/<td style="background-color:#[0-9A-F]{6};">/i', '', $answer);

i PCRE modifier 告诉 preg_replace 忽略字符大小写。

仅当颜色代码恰好包含6个十六进制数字时才进行识别和替换。为了使其使用 3-digit RGB notation 识别颜色代码,您需要将 regexp[0-9A-F]{6} 部分更改为 [0-9A-F]{3}([0-9A-F]{3})?。或者使用更简单的表达式来匹配 3 到 6 位之间的所有颜色代码:[0-9A-F]{3,6}

您也可以将 \s* 放在冒号 (:) 之后,以使其在 background-color: 部分之后出现一个或多个空格时也匹配。

更新后的代码是:

$answer = preg_replace(
    '/<td style="background-color:\s*#[0-9A-F]{3,6};">/i', '', $answer
);

但是,如果您只想匹配某些颜色,则可以将颜色代码用 | 分隔:

$answer = preg_replace(
    '/<td style="background-color:\s*#(80F9CC|E1E3E4|D1D3D4|73F6AB|3CEB88);">/i',
    '',
    $answer
);

正则表达式部分的简短解释:

<td style="background-color:    # plain text, matches if exact
\s*                             # matches zero or more (*) space characters (\s)
#                               # plain text, matches exactly one '#'
(                               # start of a group, doesn't match anything
     80F9CC                         # matches '80F9CC'
    |E1E3E4                         # or (|) 'E1E3E4'
    |D1D3D4                         # or 'D1D3D4'
    |73F6AB                         # or ...
    |3CEB88                         # or ...
)                               # end of the group    
;">                             # plain text; matches exactly this text

str_replace()可以接受一个数组作为参数:

$replace_array = [
    '<td style="background-color:#80F9CC;">',
    '<td style="background-color:#E1E3E4;">',
    '<td style="background-color:#73F6AB;">',
    '<td style="background-color:#3CEB88;">',
];

$answer = str_replace($replace_array, '', $answer);

或者您可以改用 preg_replace()