2012-04-26 52 views
0

排除名“.html”我使用下面的preg_replace()调用替换为新的结构链接:的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”。

我相信这是一些简单的我失踪,但谷歌搜索的问题并没有拿出任何有用的结果,所以我希望这里有人能帮助!

在此先感谢!

编辑:作为一个例子,这里是$链接侧连接

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

上面的例子,如果工作我改变了REGEXT但是到下面没有(*):

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

任何想法?

+0

你能告诉我们'$ links'的内容是什么? – anubhava 2012-04-26 11:51:42

+0

@Ashley:请看看我的编辑,因为我为你解决了这个问题 – Nikola 2012-04-26 12:26:14

回答

2

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

例如:

<?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)。

但是,additionaly当你使用它?它的ungready方法(这可能有助于解释: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; 
?> 

输出此链接:
<a class="prodCatThumb" title="View product" href="example.com/sub-dir/product-identifier">
现在会是:
<a class="prodCatThumb" title="View product" href="newsite.co.uk/sub-dir/product-identifier.html">

+0

这工作!你能解释一下什么是“?”为什么它修复它,所以我知道在未来?再次感谢! – Ashley 2012-04-26 11:56:58

+0

@Nikolo这不太合适......如果标记是“ “它结束为””不知何故! – Ashley 2012-04-26 12:12:02

+0

@Ashley:我编辑了我的答案,因为这里不适合 – Nikola 2012-04-26 12:19:44

0

为了更好地理解问题,我们需要查看$links的内容。

同时,你可以尝试:

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

谢谢,你的正则表达式适用于我的帖子中的第一个例子,但第二个例子根本没有改变链接! – Ashley 2012-04-26 12:16:41

+0

其实它适用于你的两个例子。如果你想,我也可以给你一个在线演示。 – anubhava 2012-04-26 12:24:24

+0

下面是现场演示:http://ideone.com/X05oM – anubhava 2012-04-26 12:27:47

0

我只是用this testing page检查你的正则表达式,它正常工作与您所提供的示例文本(<a href="http://example.com/sub-dir/the-identifier">Anchor</a>)。你确定没有别的东西会给你造成问题吗?

测试现场返回此:<a href="http://newsite.co.uk/sub-dir/the-identifier.html">Anchor</a>

+0

谢谢,请检查原始帖子以获取更新示例。 – Ashley 2012-04-26 12:14:35