这是我的完整链接。
<a href="http://localhost/mysite/client-portal/">Client Portal</a>
我希望上面的链接看起来像下面这样。
<a href="#popup">Client Portal</a>
我真的不知道如何使用 preg_replace 来完成这个任务。
preg_replace('\/localhost\/mysite\/client-portal\/', '#popup', $output)
这是我的完整链接。
<a href="http://localhost/mysite/client-portal/">Client Portal</a>
<a href="#popup">Client Portal</a>
我真的不知道如何使用 preg_replace 来完成这个任务。
preg_replace('\/localhost\/mysite\/client-portal\/', '#popup', $output)
str_replace()
来实现您的目标:<?php
$link = '<a href="http://localhost/mysite/client-portal/">Client Portal</a>';
$href = 'http://localhost/mysite/client-portal/';
$new_href = '#popup';
$new_link = str_replace($href, $new_href, $link);
echo $new_link;
?>
输出:
<a href="#popup">Client Portal</a>
<?php
$link = '<a href="http://localhost/mysite/client-portal/">Client Portal</a>';
$new_href = '#popup';
$doc = new DOMDocument;
$doc->loadHTML($link);
foreach ($doc->getElementsByTagName('a') as $link) {
$link->setAttribute('href', $new_href);
}
echo $doc->saveHTML();
?>
输出:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" "http://www.w3.org/TR/REC-html40/loose.dtd">
<html><body><a href="#popup">Client Portal</a></body></html>
preg_replace()
:<?php
$link = '<a href="http://localhost/mysite/client-portal/">Client Portal</a>';
$new_href = '#popup';
$regex = "((https?|ftp)\:\/\/)?"; // SCHEME
$regex .= "(localhost)"; // Host or IP
$regex .= "(\/([a-z0-9+\$_-]\.?)+)*\/?"; // Path
$pattern = "/$regex/";
$newContent = preg_replace($pattern, $new_href, $link);
echo $newContent;
?>
输出:
<a href="#popup">Client Portal</a>
如果您愿意,也可以使用jQuery进行操作。
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
<a class="popupClass" href="http://localhost/mysite/client-portal/">Client Portal</a>
$(document).ready(function(){
$('.popupClass').attr('href','').attr('href','#popup');
});
str_replace()
将可以很好地工作,不需要正则表达式。 - user557846