如何更改链接元素(a)中的href(url)?

3

这是我的完整链接。

<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() 将可以很好地工作,不需要正则表达式。 - user557846
你能否举个例子? - Abdul Shakoor Kakar
该手册有许多示例。 - user557846
非常感谢,这正好起作用。 - Abdul Shakoor Kakar
2个回答

2
如果您只需要这个链接,您可以使用 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>

如果您愿意,您可以使用DOM:
<?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>

1
谢谢你的回答。但是我已经像"Dagon"上面所说的那样完成了。 - Abdul Shakoor Kakar

1

如果您愿意,也可以使用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');
});

演示


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接