简体   繁体   English

正则表达式搜索+替换href =“URL”

[英]Regular Expression to Search+Replace href=“URL”

I'm useless with regular expressions and haven't been able to google myself a clear solution to this one. 我对正则表达式毫无用处,并且无法自己谷歌一个明确的解决方案。

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). 我想用一个新的url(存储为变量$ newurl)为锚点href中的任何url搜索+替换一些文本($ content)。

Change this: 改变这个:

<a href="http://blogurl.com/files/foobar.jpg"><img alt="foobar" src="http://blogurl.com/files/2011/03/foobar_thumb.jpg" /></a>

To this: 对此:

<a href="http://newurl.com/here/"><img alt="foobar" src="http://blogurl.com/files/2011/03/foobar_thumb.jpg" /></a>

I imagine using preg_replace would be best for this. 我想使用preg_replace最适合这个。 Something like: 就像是:

preg_replace('Look for href="any-url"', 
'href="$newurl"',$content);

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). 我们的想法是将WordPress首页上的所有图像链接到他们的帖子而不是全尺寸图像(这是他们默认的方式)。 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;

Mucho thanko to @WiseGuyEh Mucho thanko到@WiseGuyEh

This should do the trick- you can test it here 这应该做的 - 你可以在这里测试它

(?<=href=("|'))[^"']+(?=("|'))

It uses lookahead and lookbehind to assert that anything it matches starts with href=" or href=' and makes sure that it ends with a single or double quote. 它使用lookahead和lookbehind断言它匹配的任何东西都以href =“href ='开头,并确保它以单引号或双引号结束。

Note: the regex will not be able to determine if this is a valid html document- if there is a mix of single then double quotes used to enclose a href value, it will ignore this error! 注意:正则表达式将无法确定这是否是一个有效的html文档 - 如果混合使用单引号和双引号用于包含href值,它将忽略此错误!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM