替换html里a标签的href路由

使用场景:数据库内富文本html处理替换非本站超链接

话不多说直接上代码

/**
 * 替换单个url
 * @param $needle
  * @param $replace
  * @param $haystack
  * @return array|string|string[]
  */
private function replaceOnce($needle, $replace, $haystack) {
    $pos = strpos($haystack, $needle);
    if ($pos === false) {
        return $haystack;
    }
    return substr_replace($haystack, $replace, $pos, strlen($needle));
}

/**
 * @param string $str
  * @return string
  */
private function replaceHtmlHrefUrl(string $str) 
{
    // 获取匹配到所有url
  preg_match_all('/<a .*?href="(.*?)".*?>/is', $str, $matches);
    if (empty($matches[1])) {
        return $str;
    }
    // ["https://www.baidu_aa-bb.com", "https://c.com"]
    $urls = $matches[1];
    $_tmp = [];
    foreach ($urls as $url) {
        $tmp = explode($url, $str);
        $_tmp[] = $tmp[0]; // <p>百度是百度</p><p><a href=
  $isSelfHost = $this->isSelfHost($url);
        if (!$isSelfHost) {
            $_tmp[] = '';
        } else {
            $_tmp[] = $url;
        }
        // " target="_blank" title="百度">百度</a><br/></p><p>本站</p><p><a href="https://c.com" target="_blank" title="本站">本站</a><br/></p>"
  $str = $this->replaceOnce($tmp[0] . $url, '', $str);
    }
    // <p>百度是百度</p><p><a href="" target="_blank" title="百度">百度</a><br/></p><p>本站</p><p><a href="https://c.com" target="_blank" title="本站">本站</a><br/></p>
  return join('', $_tmp) . $str;
}
/**
 * 是否本站host
 * @param string $url
  * @return bool
  */
private function isSelfHost(string $url): bool
{
    if (empty($url)) {
        return false;
    }
    $parseUrl = parse_url($url);
    $host = data_get($parseUrl, 'host', '');
    if (empty($host)) {
        return false;
    }
    $hostArr = explode('.', $host);
    if (empty($hostArr)) {
        return false;
    }
    $hostCount = count($hostArr);
    $tmpHost = '';
    if ($hostCount == 2) {
        $hostArr0 = data_get($hostArr, 0, '');
        $hostArr1 = data_get($hostArr, 1, '');
        $tmpHost = $hostArr0 . '.' . $hostArr1;
    } elseif ($hostCount == 3) {
        $hostArr1 = data_get($hostArr, 1, '');
        $hostArr2 = data_get($hostArr, 2, '');
        $tmpHost = $hostArr1 . '.' . $hostArr2;
    }
    return in_array($tmpHost, ['a.cn', 'c.com']);
}

使用示例

$html = '"<p>百度是百度</p><p><a href="https://www.baidu_aa-bb.com" target="_blank" title="百度">百度</a><br/></p><p>本站</p><p><a href="https://c.com" target="_blank" title="本站">本站</a><br/></p>"';
        $html = $this->replaceHtmlHrefUrl($html);
        echo $html;
本作品采用《CC 协议》,转载必须注明作者和本文链接
zhaobo
《L04 微信小程序从零到发布》
从小程序个人账户申请开始,带你一步步进行开发一个微信小程序,直到提交微信控制台上线发布。
《L02 从零构建论坛系统》
以构建论坛项目 LaraBBS 为线索,展开对 Laravel 框架的全面学习。应用程序架构思路贴近 Laravel 框架的设计哲学。
讨论数量: 2

我选择直接把 xml 转数组,然后遍历数组。 openlss/lib-array2xml

1年前 评论
zhaobo (楼主) 1年前

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!
技术 @ 微擎团队
文章
1
粉丝
0
喜欢
0
收藏
0
排名:2939
访问:236
私信
所有博文
社区赞助商