【问题标题】:php regex match url contains and replace slash with dashphp正则表达式匹配url包含并用破折号替换斜杠
【发布时间】:2014-11-23 16:28:04
【问题描述】:

仅更改包含 change.com 的 url 将“/”替换为“-”并将 .html 放在末尾​​p>

<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 regex preg-replace preg-match


【解决方案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 必须完成的一些内置函数。

【讨论】:

  • 为什么要替换下划线?
  • 不工作我认为它适用于 preg_replace 我只需要将 / 替换为 - /q/photoshopbattles/comnts/2n4jtb/psbattle_asgfdhj/
  • @uyrxe:是的,我很抱歉。我误读了你想要的东西。我已经更新了您需要的答案。希望对您有所帮助。
  • 谢谢.. 我想用改变的 url 来回显完整的 $string 而不仅仅是 urls
  • 非常非常感谢,在您的帮助下,一个月后我绝对可以每月赚取 1100 美元
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-04-15
  • 1970-01-01
  • 2018-09-21
  • 1970-01-01
  • 1970-01-01
  • 2021-11-13
  • 1970-01-01
相关资源
最近更新 更多