0

我正在使用以下 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">

有任何想法吗?

4

3 回答 3

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 匹配颜色和颜色(来自此链接)。

但是,当您将它与 ? 这是未准备好的方法(这可能有助于解释:带有 .* 的正则表达式?(点星号)匹配太多?或者这个: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">

于 2012-04-26T11:53:59.057 回答
0

我们需要查看内容$links以便更好地理解问题。

同时你可以试试:

preg_replace('#example\.com/sub-dir/([^"]*)">#', 
             'newsite.co.uk/sub-dir/$1.html">', $links);
于 2012-04-26T11:54:12.203 回答
0

我刚刚使用此测试页面来检查您的正则表达式,它与您提供的示例文本 ( <a href="http://example.com/sub-dir/the-identifier">Anchor</a>) 配合得很好。你确定没有其他东西给你造成问题吗?

测试站点返回以下内容:<a href="http://newsite.co.uk/sub-dir/the-identifier.html">Anchor</a>

于 2012-04-26T12:00:03.593 回答