【问题标题】:Replacing Relative Links with External Links in PHP String用 PHP 字符串中的外部链接替换相对链接
【发布时间】:2018-12-06 02:57:58
【问题描述】:

我正在使用一个编辑器,它纯粹使用文件的内部相对链接,这对于我使用它的 99% 来说非常有用。

但是,我也使用它在电子邮件正文中插入文件的链接,而相对链接并不能解决问题。

我不想修改编辑器,而是想从编辑器中搜索字符串并将相关链接替换为外部链接,如下所示

替换

files/something.pdf

https://www.someurl.com/files/something.pdf

我想出了以下方法,但我想知道是否有更好/更有效的方法来使用 PHP

<?php
$string = '<a href="files/something.pdf">A link</a>, some other text, <a href="files/somethingelse.pdf">A different link</a>';

preg_match_all('/<a[^>]+href=([\'"])(?<href>.+?)\1[^>]*>/i', $string, $result);

if (!empty($result)) {
    // Found a link.
    $baseUrl = 'https://www.someurl.com';
    $newUrls = array();
    $newString = '';

    foreach($result['href'] as $url) {
        $newUrls[] = $baseUrl . '/' . $url;
    }

    $newString = str_replace($result['href'], $newUrls, $string);

    echo $newString;
}
?>

非常感谢

【问题讨论】:

    标签: php regex preg-match preg-match-all


    【解决方案1】:

    您可以简单地使用preg_replace 替换所有出现在双引号内的以 URL 开头的文件:

    $string = '<a href="files/something.pdf">A link</a>, some other text, <a href="files/somethingelse.pdf">A different link</a>';
    
    $string = preg_replace('/"(files.*?)"/', '"https://www.someurl.com/$1"', $string);
    

    结果是:

    <a href="https://www.someurl.com/files/something.pdf">A link</a>, some other text, <a href="https://www.someurl.com/files/somethingelse.pdf">A different link</a>
    

    【讨论】:

      【解决方案2】:

      你确实应该使用 DOMdocument 来完成这样的工作,但是如果你想使用正则表达式,那么这个就可以了:

      $string = '<a some_attribute href="files/something.pdf" class="abc">A link</a>, some other text, <a class="def" href="files/somethingelse.pdf" attr="xyz">A different link</a>';
      $baseUrl = 'https://www.someurl.com';
      $newString = preg_replace('/(<a[^>]+href=([\'"]))(.+?)\2/i', "$1$baseUrl/$3$2", $string);
      echo $newString,"\n";
      

      输出:

      <a some_attribute href="https://www.someurl.comfiles/something.pdf" class="abc">A link</a>, some other text, <a class="def" href="https://www.someurl.com/files/somethingelse.pdf" attr="xyz">A different link</a>
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-02-18
        • 1970-01-01
        • 2020-06-16
        • 2011-04-19
        • 1970-01-01
        • 1970-01-01
        • 2011-02-21
        相关资源
        最近更新 更多