【问题标题】:How to change the href (url) in a link (a) element?如何更改链接(a)元素中的href(url)?
【发布时间】:2015-06-20 20:19:15
【问题描述】:

这是我的完整链接。

<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 jquery html regex string


【解决方案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');
});

Demo

【讨论】:

    【解决方案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>
    

    【讨论】:

    • 感谢您的回答。但我已经按照上面的“Dagon”所说的那样做了。
    猜你喜欢
    • 2021-09-15
    • 1970-01-01
    • 1970-01-01
    • 2015-10-24
    • 2019-09-05
    • 2019-12-11
    • 2015-09-17
    • 2014-03-24
    • 1970-01-01
    相关资源
    最近更新 更多