从所有锚标记中删除除 href 和 target(如果 target != '')之外的所有属性

Remove all attributes except href and target (if target != '') from all anchor tags

我有一个 html 字符串,需要删除除 href 和 target 之外的所有锚标记属性(如果 target 具有有效值)。

$content = '<p style="abc" rel="blah blah"> Hello I am p </p> <a href="https://example.com/abc" target="_blank" rel="noopener noreferrer"></a>';

我已经为此创建了一个正则表达式 -

preg_replace('/<a\s+[^>]*href\s*=\s*"([^"]+)"[^>]*>/', '<a href="">', $content)

但这也会删除目标属性,即使它具有有效值 (_blank)。

例如 -

<a href="https://example.com/abc" target="_blank" rel="noopener noreferrer"></a>

应该return

<a href="https://example.com/abc" target="_blank"></a>

<a href="https://example.com/abc" target="" rel="noopener noreferrer"></a>

应该return

<a href="https://example.com/abc"></a>

尝试使用以下正则表达式:

preg_replace('/(\s?target=(?:""))?(\srel.+")\s?/', ' ', $content)

我只测试了您提供的两个示例,如果某些模式不适用,请分享一些示例。

注:Online demo for testing

您可以采取不同的方法。比如只提取 target 属性和元素内容,然后用它们创建一个新元素。

$content   = '<a href="https://example.com/abc" target="_blank" rel="noopener noreferrer">click here</a>';

// Extract the content.

$value     = array();
$has_value = preg_match( '/<[^<>]+>([^<>]*)<\/[^<>]+>/', $content, $value );

if ( $has_value ) {
    $value = $value[1];
} else {
    $value = '';
}

// Extract the target attribute.

$target_attr = array();
$has_target  = preg_match( '/[\s<]target="[^"]+"[\s>]/', $content, $target_attr );

if ( $has_target ) {
    $target_attr = $target_attr[0];
} else {
    $target_attr = '';
}

$new_content = "<a $target_attr>$value</a>";

输出:

<a  target="_blank" >click here</a>

希望对您有所帮助:)