php - 如何用 if/not 有条件地替换文本
问题描述
抓取网页的 html 后,我需要有条件地替换文本以更正指向资源和媒体的链接。
我需要通过将 'href="/' 替换为 'href="http://example.com/' 来替换本地链接,这样链接才能正常工作,但同时排除诸如 'href="//' 之类的任何内容链接到不使用“http:/https:”的非现场资源以兼容和不兼容 SSL。所以......
如果 'href="/' 或 'href=/'
但如果 'href="//' 或 'href=//' 则不是
这并没有取代任何东西......
$html = str_replace('href="?/(?!/)', $url, $html);
同时,我首先替换//:
$html = str_replace('href="//', 'href="https://', $html);
$html = str_replace('href=//', 'href=https://', $html);
解决方案
您需要preg_replace
用于正则表达式替换,而不是str_replace
:
$tests = array("<a href=\"/", "<a href=/", "<a href=\"//", "<a href=//");
$pattern = '/href=("?)\/(?!\/)/';
foreach ($tests as $test) {
echo preg_replace($pattern, "href=\\1http://example.com/", $test);
echo "\n";
}
输出:
<a href="http://example.com/
<a href=http://example.com/
<a href="//
<a href=//
推荐阅读
- html - 当我添加导航栏时,我的内容下方会添加空格。我该如何删除这个?
- javascript - Electron 收据热敏打印机
- javascript - 无法使用 API 密钥作为环境变量与 asyncData() 中的 Butter CMS 库
- ruby-on-rails - 如何使用 pry 在 Rails 控制台中回滚失败的事务
- tensorflow - ValueError:您正在尝试将包含 5 层的权重文件加载到具有 0 层的模型中
- python - 无法理解 scipy.sparse.csr_matrix 示例
- python-3.x - 我怎样才能让代理以很小的概率跳跃?
- assembly - 如何从 ARM 中的命令行计算字符串长度?
- bash - 使用 for 循环读取时匹配文件
- python - 返回分类系列的分类标签