我正在使用一个编辑器,它只与文件的内部相对链接一起工作,这对我使用它的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;
}
?>
非常感谢
李
发布于 2018-06-27 09:42:30
您可以简单地使用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>
发布于 2018-06-27 12:21:32
你真的应该使用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>
https://stackoverflow.com/questions/51058955
复制