替换本地链接,保留外部链接

发布于 2024-07-16 23:26:23 字数 500 浏览 2 评论 0 原文

我有一个 API 调用,它本质上返回托管 wiki 应用程序页面的 HTML。 然后我根据我的网站风格指南进行一些 substr、str_replace 和 preg_replace 功夫来格式化它。

我做了一组调用来格式化我的左侧导航(将 pageX 的链接更改为我的 wikiParse?page=pageX 类型的东西)。 我可以安全地在左侧导航上执行此操作。 然而,在正文中,我不能安全地假设链接是指向内部页面的链接。 它很可能是指向外部资源的链接。 所以我需要做一个 preg_replace 匹配 href= ,后面不跟着 http:// 。

这是我的尝试:

$result = preg_replace('href\=\"(?!http\:\/\/)','href="bla?id=',$result);

这似乎删除了页面上的全部内容。 有人看出我哪里出错了吗? 我不认为我离得太远,只是不知道下一步该去哪里。

干杯

I have an API call that essentially returns the HTML of a hosted wiki application page. I'm then doing some substr, str_replace and preg_replace kung-fu to format it as per my sites style guides.

I do one set of calls to format my left nav (changing a link to pageX to my wikiParse?page=pageX type of thing). I can safely do this on the left nav. In the body text, however, I cannot safely assume a link is a link to an internal page. It could very well be a link to an external resource. So I need to do a preg_replace that matches href= that is not followed by http://.

Here is my stab at it:

$result = preg_replace('href\=\"(?!http\:\/\/)','href="bla?id=',$result);

This seems to strip out the entire contents on the page. Anyone see where I slipped up? I don't think I'm too far off, just can't see where to go next.

Cheers

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

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

发布评论

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

评论(2

(り薆情海 2024-07-23 23:26:23

preg_* 函数 期望 Perl 兼容正则表达式 (PCRE)。 与普通正则表达式的结构差异在于,表达式本身被包装在分隔符中,该分隔符将表达式与可能的 修饰符。 经典的分隔符是 /,但 PHP 允许除反斜杠字符之外的任何其他非字母数字字符。 另请参阅PHP PCRE 简介

所以试试这个:

$result = preg_replace('/href="(?!http:\/\/)/', 'href="bla?id=', $result);

这里 href="(?!http://) 是正则表达式。但是当我们使用 / 作为分隔符时,出现 /正则表达式内的 必须使用反斜杠进行转义。

The preg_* functions expect Perl-Compatible Regular Expressions (PCRE). The structural difference to normal regular expressions is that the expression itself is wrapped into delimiters that separate the expression from possible modifiers. The classic delimiter is the / but PHP allows any other non-alphanumeric character except the backslash character. See also Intruduction to PCRE in PHP.

So try this:

$result = preg_replace('/href="(?!http:\/\/)/', 'href="bla?id=', $result);

Here href="(?!http://) is the regular expression. But as we use / as delimiters, the occurences of / inside the regular expression must be escaped using backslashes.

将军与妓 2024-07-23 23:26:23

您的正则表达式缺少开始和结束分隔符(默认为“/”);

$result = preg_replace('/href\=\"(?!http\:\/\/)/','href="bla?id=',$result);

Your regexp is missing starting and ending delimiters (by default '/');

$result = preg_replace('/href\=\"(?!http\:\/\/)/','href="bla?id=',$result);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文