我试图让我的 PHP 代码从包含属性 data-class="false" 的链接中删除 class="something" 并保留其他链接。
$mytext = 'text text text <a href="/url" data-class="false" class="something">
link1</a> text text text <a href="/url" class="something">link2</a> text text
text <a href="/url" class="something" data-class="false">link3</a> text text
text';
// This function is supposed to remove the class="something" string from matches.
function remove_class($matches) {
return str_replace(' class="something"','', $matches[1]);
}
// Match any link that contains the data-class="false" string and do callback.
$mytext = preg_replace_callback('/<a.*?data-class="false".*?>/',
'remove_class', $mytext);
echo $mytext;
期望的结果如下:(注意在 data-class="false" 存在的地方删除了该类)
text text text <a href="/url" data-class="false">link1</a> text text text
<a href="/url" class="something">link2</a> text text text
<a href="/url" data-class="false">link3</a> text text text