将没有 link 的所有 <a> 元素的 href 值替换为 .mp3 扩展名
Replacing href value of all <a> elemnts without link with .mp3 extention
这是我创建的 php 代码,用于将 href 值替换为新的 url
$string = "<a href='http://example.com/test'>click here</a>
<a href='http://example.com/test.mp3'>the site</a>";
$newurl = "http://newurl.com";
$pattern = "/(?<=href=(\"|'))[^\"']+(?=(\"|'))/";
$newstring = preg_replace($pattern,$newurl,$string);
echo $newstring;
现在我想要 links with .mp3 or .zip extensions not Replacing to new link
示例:我想将“http://example.com/post/1”替换为 "http://myotherexample.com/test"
如果 link url 是 "http://example.com/test.mp3"
不替换并显示常规 url
点赞输出
查看源代码:
<a href='http://myotherexample.com'>click here</a>
<a href='http://example.com/test.mp3'>the site</a>
使用否定前瞻:
$string = "<p>Please <a href='http://example.com'>click here</a> to go to <a href='http://example.com/test.mp3'>the site</a></p>";
$newurl = "http://myotherexample.com";
// Edit according to comment
$pattern = "/(?<=href=(\"|'))[^\"']+\.(?!(?:mp3|zip))(?:\/?\?[^\"']*)?(?=(\"|'))/";
$newstring = preg_replace($pattern,$newurl,$string);
echo $newstring;
输出:
<p>Please <a href='http://myotherexample.com'>click here</a> to go to <a href='http://example.com/test.mp3'>the site</a></p>
(<a[^>]*?href\s*=\s*['"](?![^'"]*mp3))[^'"]*
这将匹配您的 <a...>
,其中包含 href
,但未找到 mp3
。它会捕获开始引号之前的文本,然后匹配直到结束引号,因此您可以将 URL 更改为您想要的任何内容。
Example and you can use the code generator在站点左侧获取PHP版本如何match/replace这个。
这是我创建的 php 代码,用于将 href 值替换为新的 url
$string = "<a href='http://example.com/test'>click here</a>
<a href='http://example.com/test.mp3'>the site</a>";
$newurl = "http://newurl.com";
$pattern = "/(?<=href=(\"|'))[^\"']+(?=(\"|'))/";
$newstring = preg_replace($pattern,$newurl,$string);
echo $newstring;
现在我想要 links with .mp3 or .zip extensions not Replacing to new link
示例:我想将“http://example.com/post/1”替换为 "http://myotherexample.com/test"
如果 link url 是 "http://example.com/test.mp3"
不替换并显示常规 url
点赞输出
查看源代码:
<a href='http://myotherexample.com'>click here</a>
<a href='http://example.com/test.mp3'>the site</a>
使用否定前瞻:
$string = "<p>Please <a href='http://example.com'>click here</a> to go to <a href='http://example.com/test.mp3'>the site</a></p>";
$newurl = "http://myotherexample.com";
// Edit according to comment
$pattern = "/(?<=href=(\"|'))[^\"']+\.(?!(?:mp3|zip))(?:\/?\?[^\"']*)?(?=(\"|'))/";
$newstring = preg_replace($pattern,$newurl,$string);
echo $newstring;
输出:
<p>Please <a href='http://myotherexample.com'>click here</a> to go to <a href='http://example.com/test.mp3'>the site</a></p>
(<a[^>]*?href\s*=\s*['"](?![^'"]*mp3))[^'"]*
这将匹配您的 <a...>
,其中包含 href
,但未找到 mp3
。它会捕获开始引号之前的文本,然后匹配直到结束引号,因此您可以将 URL 更改为您想要的任何内容。
Example and you can use the code generator在站点左侧获取PHP版本如何match/replace这个。