仅当 url 不以 http:// 开头时,正则表达式才用字符串替换部分 url

发布于 2025-01-02 08:04:20 字数 191 浏览 3 评论 0原文

试图在堆栈溢出上找到答案,但我是一个十足的正则表达式菜鸟!

我所需要的(如果可能的话)就是在某些 HTML 中匹配 PDF URL,如果它不是以 http:// 开头,则将 /content/ 添加到开头,如果它确实以 http:// 开头,则不执行任何操作。

Tried to find the answer on stackoverflow but I'm a complete RegEx noob!

All I need (if it's possible) is to match a PDF URL in some HTML and if it doesn't start with http:// add /content/ to the start, if it does start with http:// do nothing.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

旧故 2025-01-09 08:04:21

你想要的正则表达式可能是

http://add/content/\S+?\.pdf

它说它必须以“http://add/content/”开头,然后可以有任何不是空白的东西,直到最后达到.pdf。
根据您使用的语言,您需要以不同的方式应用它。例如在 php 中它是

preg_match_all('|http://add/content/\S+?\.pdf|',$html,$matches);
if(count($matches)) {
     //do stuff with the matches in the $matches array
} else {
     //there were no matches of that form
}

The regex you want is probably

http://add/content/\S+?\.pdf

Which says it must start with "http://add/content/" then can have anything which isn't a whitespace until it hits a .pdf at the end.
Depending on what language you use you will need to apply this differently. For example in php it would be

preg_match_all('|http://add/content/\S+?\.pdf|',$html,$matches);
if(count($matches)) {
     //do stuff with the matches in the $matches array
} else {
     //there were no matches of that form
}
听风念你 2025-01-09 08:04:21

假设你想用 javascript 来做到这一点。

var links = document.getElementsByTagName("a");
for(var i = 0; i < links.length; i++){
    var link = links[i];
    var href = link.getAttribute("href");
    if(!/^http/.test(href))
    {
        link.setAttribute("href", "/content/" + href);
    }
}

Assuming you want to do this with javascript.

var links = document.getElementsByTagName("a");
for(var i = 0; i < links.length; i++){
    var link = links[i];
    var href = link.getAttribute("href");
    if(!/^http/.test(href))
    {
        link.setAttribute("href", "/content/" + href);
    }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文