删除标签<a> to a specific URL domain php

时间:2019-03-05 16:13:00

标签: php regex preg-match-all

This is a script code that is not mine, I try to modify it. What it does search for all the tags and then delete them. How would you modify the code to erase only the tags of a given domain or url? for example, delete the domain tags: www.domainurl.com , Remove all tags as:

     <a href="https://www.domainurl.com/refer/google-adsense/">fsdf</a>
    <a title="Google Adsense" href="https://www.domainurl.com/refer/google-adsense/" target="_blank" rel="nofollow noopener">fgddf</a>
    <a href="https://www.domainurl.com/page/pago">domain </a>
<a title="Google Adsense" href="https://www.googlead.com/refer/google-adsense/" target="_blank" rel="nofollow noopener">googled</a>

result would look like this:

fsdf
fgddf
domain
<a title="Google Adsense" href="https://www.googlead.com/refer/google-adsense/" target="_blank" rel="nofollow noopener">google</a>

This is the code :

if (in_array ( 'OPT_STRIP', $camp_opt )) {
                          echo '<br>Striping links ';

                        //$abcont = strip_tags ( $abcont, '<p><img><b><strong><br><iframe><embed><table><del><i><div>' );


                        preg_match_all('{<a.*?>(.*?)</a>}' , $abcont , $allLinksMatchs);


                        $allLinksTexts    = $allLinksMatchs[1];
                        $allLinksMatchs=$allLinksMatchs[0];


                        $j = 0;
                        foreach ($allLinksMatchs as $singleLink){

                            if(! stristr($singleLink, 'twitter.com'))
                            $abcont = str_replace($singleLink, $allLinksTexts[$j], $abcont);

                            $j++;
                        }
}

I tried doing this but it did not work for me:

Regex :

Specifying in the search with preg_match_all

 preg_match_all('{<a.*?[^>]* href="((https?:\/\/)?([\w\-])+\.{1}domainurl\.([a-z]{2,6})([\/\w\.-]*)*\/?)">(.*?)</a>}' , $abcont , $allLinksMatchs);

Any ideas? , I would thank you a lot

3 个答案:

答案 0 :(得分:4)

我没有选择像您建议的那样使用parse HTML with regular expressions,而是选择使用DOMDocument类。

function remove_domain($str, $domainsToRemove)
{
    $domainsToRemove = is_array($domainsToRemove) ? $domainsToRemove : array_slice(func_get_args(), 1);

    $dom = new DOMDocument;
    $dom->loadHTML("<div>{$str}</div>", LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD);

    $anchors = $dom->getElementsByTagName('a');
    // Code taken and modified from: http://php.net/manual/en/domnode.replacechild.php#50500
    $i = $anchors->length - 1;
    while ($i > -1) {
        $anchor = $anchors->item($i);

        foreach ($domainsToRemove as $domain) {
            if (strpos($anchor->getAttribute('href'), $domain) !== false) {
                // $new = $dom->createElement('p', $anchor->textContent);
                $new = $dom->createTextNode($anchor->textContent);

                $anchor->parentNode->replaceChild($new, $anchor);
            }
        }

        $i--;
    }

    // Create HTML string, then remove the wrapping div.
    $html = $dom->saveHTML();
    $html = substr($html, 5, strlen($html) - (strlen('</div>') + 1) - strlen('<div>'));

    return $html;
}

然后可以在以下示例中使用上面的代码。
请注意,如何将字符串作为要删除的域进行传递,或者可以传递域的数组,也可以利用func_get_args并传递无限数量的参数。

$str = <<<str
     <a href="https://www.domainurl.com/refer/google-adsense/">fsdf</a>
    <a title="Google Adsense" href="https://www.domainurl.com/refer/google-adsense/" target="_blank" rel="nofollow noopener">fgddf</a>
    <a href="https://www.domainurl.com/page/pago">domain </a>
<a title="Google Adsense" href="https://www.googlead.com/refer/google-adsense/" target="_blank" rel="nofollow noopener">googled</a>
str;

// Example usage
remove_domain($str, 'domainurl.com');
remove_domain($str, 'domainurl.com', 'googlead.com');
remove_domain($str, ['domainurl.com', 'googlead.com']);

首先,我已经将您的字符串存储在变量中,但这只是为了使我可以将其用于答案;将$str替换为从中获取该代码的任何地方。

loadHTML函数采用HTML字符串,但需要一个子元素-因此,为什么要将字符串包装在div中。

while循环将迭代定位元素,然后仅使用定位标记的内容替换匹配指定域的任何内容。
请注意,我在此行上方留下了注释,您可以代替使用。这将用p标签替换锚元素,该标签的默认样式为display: block;,这意味着您的布局不太可能损坏。但是,由于您的预期输出只是文本节点,因此我只剩下一个选择。

Live demo

答案 1 :(得分:2)

那又怎么样:

<a.*? href=\".*www\.googlead\.com.*\">(.*?)<\/a>

它变成:

preg_match_all('{<a.*? href=\".*www\.googlead\.com.*\">(.*?)<\/a>}' , $abcont , $allLinksMatchs);

这将从a中仅删除www.googlead.com个标签。

您可以检查正则表达式结果here

答案 2 :(得分:0)

假设您的HTML包含在以下变量中。

使用preg_replace应该是一个更好的选择,下面的函数应该对您有所帮助:

function removeLinkTagsOfDomain($html, $domain) {
    // Escape all regex special characters
    $domain = preg_quote($domain);

    // Search for <a> tags with a href attribute containing the specified domain
    $pattern = '/<a .*href=".*' . $domain . '.*".*>(.+)<\/a>/';

    // Final replacement (should be the text node of <a> tags)
    $replacer = '$1';

    return preg_replace($pattern, '$1', $html);
}

// Usage:

$domains = [...];
$html = '...';

foreach ($domains as $d) {
    $html = removeLinkTagsOfDomain($html, $d);
}