preg_replace 模式不适用于 HTML 标签

preg_replace pattern doesn't work with HTML tags

我正在使用 preg_replace 模式从字符串 ($subject) 中替换关键字 ($search) 的第 n 个实例 ($occurrence)。

$search = preg_quote($search);
return preg_replace("/^((?:(?:.*?$search){".--$occurrence."}.*?))$search/", "$replace", $subject);
}

该模式适用于纯文本,但如果有 HTML 标签,例如 <br />,它将停止。

我不太了解正则表达式,我的代码来自 here

我需要帮助修复模式以忽略 HTML 标签的存在。

编辑: 原来问题不在于 HTML 标签。问题是换行符。

如果 $subject 有换行符,它将无法匹配第一个换行符后的 $search

示例:

$subject = 'This is the first line
This is the second line
This is the third line';

现在尝试匹配第三行关键字的第二个,它不会起作用。

多行搜索需要在regex末尾添加s,这样出现换行的时候会继续搜索。

更多阅读link

这有效吗?

$search = preg_quote($search);
return preg_replace("/^((?:(?:.*?$search){".--$occurrence."}.*?))$search/s", "$replace", $subject);
}