【问题标题】:preg_replace is excluding ".html" from the replace clausepreg_replace 从替换子句中排除“.html”
【发布时间】:2012-07-31 03:51:36
【问题描述】:

我正在使用以下 preg_replace() 调用来用新结构替换链接:

preg_replace('/example.com\/sub-dir\/(.*)">/', 'newsite.co.uk/sub-dir/$1.html">', $links);

它几乎可以工作,除了它没有将“.html”添加到替换的末尾,所以它最终像“newsite.co.uk/sub-dir/page-identifier”而不是“newsite.co.uk/sub-dir/page-identifier.html”。

我确信我错过了一些简单的事情,但是谷歌搜索问题并没有得出任何有用的结果,所以我希望这里有人可以提供帮助!

提前致谢!

编辑:例如,这里是 $links 的链接端

<a href="http://example.com/sub-dir/the-identifier">Anchor</a>

如果我将正则表达式更改为 (.*?) 则上述示例有效,但以下示例无效:

<a class="prodCatThumb" title="View product" href="http://example.com/sub-dir/product-identifier">

结果是

<a class="prodCatThumb.html" title="View product" href="http://example.com/sub-dir/product-identifier">

有什么想法吗?

【问题讨论】:

  • 你能告诉我们$links的内容吗?
  • @Ashley:请看我的编辑,因为我已经为你解决了这个问题

标签: php preg-replace


【解决方案1】:

是的,是关于.*
只需像这样添加?.*?

示例:

<?php
    $links = "example.com/sub-dir/myfile.php";
    $links = preg_replace('/example.com\/sub-dir\/(.*?)/', 'newsite.co.uk/sub-dir/$1.html', $links);
    echo $links;
?>

编辑: @Ashley:当然,问号使正则表达式中的前面的标记是可选的。例如:colou?r 匹配颜色和颜色(来自this link)。

但是,当您将它与 ?这是未准备好的方法(这可能有助于解释:Regular expression with .*? (dot-star-questionmark) matches too much? 或此:http://www.phpro.org/tutorials/Introduction-to-PHP-Regex.html

所以,回答你的qq:

<?php
    $links = '<a class="prodCatThumb" title="View product" href="example.com/sub-dir/product-identifier">';
    $links = preg_replace('/example.com\/sub-dir\/(.*?)"/', 'newsite.co.uk/sub-dir/$1.html"', $links);
    echo $links;
?>

此链接的输出:
&lt;a class="prodCatThumb" title="View product" href="example.com/sub-dir/product-identifier"&gt;
现在是:
&lt;a class="prodCatThumb" title="View product" href="newsite.co.uk/sub-dir/product-identifier.html"&gt;

【讨论】:

【解决方案2】:

我们需要查看$links的内容才能更好地理解问题。

同时你可以试试:

preg_replace('#example\.com/sub-dir/([^"]*)">#', 
             'newsite.co.uk/sub-dir/$1.html">', $links);

【讨论】:

  • 谢谢,您的正则表达式适用于我帖子中的第一个示例,但第二个示例根本不会更改链接!
  • 实际上它适用于您的两个示例。如果你愿意,我也可以给你一个在线演示。
【解决方案3】:

我刚刚使用this testing page 来检查您的正则表达式,它适用于您提供的示例文本 (&lt;a href="http://example.com/sub-dir/the-identifier"&gt;Anchor&lt;/a&gt;)。您确定没有其他问题给您造成问题吗?

测试站点返回这个:&lt;a href="http://newsite.co.uk/sub-dir/the-identifier.html"&gt;Anchor&lt;/a&gt;

【讨论】:

  • 谢谢,请查看原始帖子以获取更新的示例。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-03-03
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多