dsn5510 2015-04-15 02:31
浏览 253
已采纳

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

Here is my full link.

<a href="http://localhost/mysite/client-portal/">Client Portal</a>

I want above link to look like following.

<a href="#popup">Client Portal</a>

I really don't know how to work with preg_replace to get this done.

preg_replace('\/localhost\/mysite\/client-portal\/', '#popup', $output)
  • 写回答

2条回答 默认 最新

  • douhu5837 2015-04-15 03:37
    关注

    If is only this link you can achieve your goal with 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;
    
    ?>
    

    Output:

    <a href="#popup">Client Portal</a>
    

    If you want you can use 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();
    
    ?>
    

    Output:

    <!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>
    

    Or you can use preg_replace() like this:

    <?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;
    
    ?>
    

    Output:

    <a href="#popup">Client Portal</a>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?