正则表达式搜索+替换 href=“URL" [英] Regular Expression to Search+Replace href="URL"
问题描述
我对正则表达式毫无用处,也无法在 google 上找到明确的解决方案.
I'm useless with regular expressions and haven't been able to google myself a clear solution to this one.
我想用新的 url(存储为变量 $newurl)搜索+替换锚点的 href 内任何 url 的一些文本 ($content).
I want to search+replace some text ($content) for any url inside the anchor's href with a new url (stored as the variable $newurl).
改变这个:
<a href="http://blogurl.com/files/foobar.jpg"><img alt="foobar" src="http://blogurl.com/files/2011/03/foobar_thumb.jpg" /></a>
对此:
<a href="http://newurl.com/here/"><img alt="foobar" src="http://blogurl.com/files/2011/03/foobar_thumb.jpg" /></a>
我想使用 preg_replace 最适合这个.类似的东西:
I imagine using preg_replace would be best for this. Something like:
preg_replace('Look for href="any-url"',
'href="$newurl"',$content);
我们的想法是让 WordPress 首页上的所有图片链接到他们的帖子,而不是全尺寸图片(这是他们默认的方式).通常只有一个 url 需要替换,但我认为替换所有可能的匹配项不会有什么坏处.
The idea is to get all images on a WordPress front page to link to their posts instead of to full sized images (which is how they default). Usually there would be only one url to replace, but I don't think it would hurt to replace all potential matches.
希望一切都有意义,并提前致谢!
Hope all that made sense and thanks in advance!
推荐答案
这是我想出的要点.希望它可以帮助某人:
Here is the gist of what I came up with. Hopefully it helps someone:
$content = get_the_content();
$pattern = "/(?<=href=(\"|'))[^\"']+(?=(\"|'))/";
$newurl = get_permalink();
$content = preg_replace($pattern,$newurl,$content);
echo $content;
非常感谢@WiseGuyEh
Mucho thanko to @WiseGuyEh
这篇关于正则表达式搜索+替换 href=“URL"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!