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

php正则表达式匹配url包含并用破折号替换斜杠,php,regex,preg-replace,preg-match,Php,Regex,Preg Replace,Preg Match,仅更改包含Change.com的url将“/”替换为“-”,并将.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>

仅更改包含Change.com的url将“/”替换为“-”,并将.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>

请帮助我,我曾多次尝试使用正则表达式,但都失败了。

这里有一种方法可以实现这一点,但它将正则表达式与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;
$string=''
. ''
. '';
//用于匹配URL的正则表达式
$pattern='/href=“(http:\/\/www.change.com\/)([^“>]*)”/;
preg_match_all($pattern,$string,$matches,preg_SET_ORDER);
foreach($匹配为$val){
//修剪结束斜杠(如果存在),替换URL路径宽度a-中的斜杠,并添加.html
$newUrl=$val[1]。str_replace(“/”,“-”,trim($val[2],“/”)。'.html';
$string=str_replace($val[0],'href=“.$newUrl.”,$string);
}
echo$字符串;

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

这里我创建了一些函数为什么要替换下划线?不起作用我认为它可以与preg_replace一起使用-/q/photoshopbattles/comnts/2n4jtb/psbattle_asgfdhj替换。是的,我道歉。我sread你想要什么。我已经更新了你需要的答案。希望能有帮助。谢谢..我想用更改的url回显完整的$string不仅仅是urlsvery非常感谢我在一个月后通过你的帮助每月肯定能赚1100美元
$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;