删除所有锚标签中除href和target(如果target != '')以外的所有属性。

问题描述 投票:0回答:1

我有一个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>';

我已经创建了一个相同的regex。

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

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

例如

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

应回

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

AND

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

应回

<a href="https://example.com/abc"></a>
php html regex preg-replace
1个回答
0
投票

用下面的regex试试。

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

我只用你提供的两个例子进行了测试,如果对某些模式无效,请分享一些例子。

注意 在线测试演示


0
投票

你可以采取不同的方法。比如只提取 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>

希望对你有帮助:)

© www.soinside.com 2019 - 2024. All rights reserved.