php 检查字符串中的每个URL以删除某些站点的链接

lqfhib0f  于 2023-01-08  发布在  PHP
关注(0)|答案(1)|浏览(132)

我想删除字符串中某些站点的URL
我用了这个:

<?php

$URLContent = '<p><a href="https://www.google.com/">Google</a></p><p><a href="https://www.anothersite.com/">AnotherSite</a></p>';

$LinksToRemove = array('google.com', 'yahoo.com', 'msn.com');
$LinksToCheck = in_array('google.com' , $LinksToRemove);

if (strpos($URLContent, $LinksToCheck) !== 0) {
    $URLContent = preg_replace('#<a.*?>([^>]*)</a>#i', '$1', $URLContent);
}

echo $URLContent;

?>

In this example, I want to remove URLs of google.com, yahoo.com and msn.com websites only if any of them found in string $URLContent, but keep any other links.
上一个代码的结果是:

<p>Google</p><p>AnotherSite</p>

但我希望它是

<p>Google</p><p><a href="https://www.anothersite.com/">AnotherSite</a></p>
xzlaal3s

xzlaal3s1#

一种解决方案是分解您的$URLContent并比较$LinksToCheck中的每个值。
可能是这样的:

<?php
$URLContent = '<p><a href="https://www.google.com/">Google</a></p><p><a href="https://www.anothersite.com/">AnotherSite</a></p>';

$urlList = explode('</p>', $URLContent);

$LinksToRemove = array('google.com', 'yahoo.com', 'msn.com');

$urlFormat = [];
foreach ($urlList as $url) {
    foreach ($LinksToRemove as $link) {
        if (str_contains($url, $link)) {
            $url = '<p>' . ucfirst(str_replace('.com', '', $link)) . '</p>';
            break;
        }
    }
    $urlFormat[] = $url;
}

$result = implode('', $urlFormat);

相关问题