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

时间:2014-11-23 16:28:05

标签: php regex preg-replace preg-match

仅更改包含change.com替换的网址" /"用" - "并把.html放在最后

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

我需要结果链接

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

请帮助我,我尝试了很多时间与正则表达式但失败了。

1 个答案:

答案 0 :(得分:1)

这是实现此目的的一种方法,但它将正则表达式与PHP函数结合使用。这种方法比纯正则表达式解决方案简单。

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

我使用正则表达式来帮助找到需要修改的URL,然后使用PHP完成工作的一些内置函数。