PHP 正则表达式匹配 URL 包含并将斜杠替换为破折号


php regex match url contains and replace slash with dash

仅更改包含 change.com 将"/"替换为"-"并将.html放在末尾的url

<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

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

这是实现此目的的一种方法,但它将正则表达式与 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 必须完成工作的一些内置函数。