替换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 协议》,转载必须注明作者和本文链接
推荐文章: