dongzh1988 2014-11-23 16:28
浏览 112
已采纳

php正则表达式匹配url包含并用破折号替换斜杠

Change only url which contains change.com replace "/" with "-" and put .html at end

<a href="http://www.notchange.com/adf/i18n/wiki/" class="coasfs" >as3rc</a>

<a href="http://www.change.com/q/photoshopbattles/comnts/2n4jtb/psbattle_asgfdhj/" class="coasfs" >as3rc</a>

<a href="http://www.change.com/q/photottles/commes/" class="coefs" >ase3rc</a>

i need result link bellow

http://www.change.com/q-photoshopbattles-comments-2n4jtb-psbattle_asgfdhj.html

please help me i tried many time with regex but failed.

  • 写回答

1条回答 默认 最新

  • dongqiu7365 2014-11-23 17:02
    关注

    Here's one way to accomplish this, but it uses Regexes in conjunction to PHP functions. This method will be simpler than a pure Regex solution.

    $string = '<a href="http://www.notchange.com/adf/i18n/wiki/" class="coasfs" >as3rc</a>'
        . '<a href="http://www.change.com/q/photoshopbattles/comnts/2n4jtb/psbattle_asgfdhj/" class="coasfs" >as3rc</a>'
        . '<a href="http://www.change.com/q/photottles/commes/" class="coefs" >ase3rc</a>';
    
    //The regex used to match the URLs
    $pattern = '/href="(http:\/\/www.change.com\/)([^">]*)"/';
    
    preg_match_all($pattern, $string, $matches, PREG_SET_ORDER);
    
    foreach ($matches as $val) {
        //trim the ending slash if exists, replace the slashes in the URL path width a -, and add the .html
        $newUrl = $val[1] . str_replace("/", "-", trim($val[2], "/")) . '.html';
    
        $string = str_replace($val[0], 'href="' . $newUrl . '"', $string);
    }
    echo $string;
    

    I used the regex to help find the urls that need to be modified, then use some built-in functions that PHP has to finish the job.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

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