如何通过 RegEx-PHP 更改 HTML 字符串中的“基本 Url”

我正在开发一个需要解析和操作 HTML 的项目。我需要替换 HTML 字符串中的“Base Url”。我正在尝试使用正则表达式来达到此目的。我尝试了多种模式,但没有运气。下面是我当前的代码 -


<?php

$html = '<html><head><base href="/" /></head><body></body></html>';

$base = 'https://SOME_URL/';


$output = preg_replace('/<base href="(.+)">/', $base, $html);


print $output;

电流输出 -


 $html = '<html><head><base href="/" /></head><body></body></html>';


预期输出 -


 $html = '<html><head><base href="https://SOME_URL/" /></head><body></body></html>';


肥皂起泡泡
浏览 80回答 2
2回答

翻过高山走不出你

您的正则表达式 -&nbsp;<base href="(.+)">, 不匹配,因为后面的部分"(.+)"是错误的。查看源字符串 -<base href="/" />看到了吗 ?和/?然后是.&nbsp;>_这只是使用正则表达式解析 HTML 不是一个好主意的众多原因之一。即使没有那个空格,甚至可能没有那个,该元素也是完全有效的/。但是,如果您 100% 确信该元素的位置base不会变得太复杂(例如大量嵌套、属性之间的新行等)。你也许可以通过——/<base[ ]*?href=".+"/i查看演示在 PHP 中,为了获得预期的输出,你可以这样做-$base = 'https://SOME_URL/';$output = preg_replace('/(<base[ ]*?href=").+(")/', "$1$base$2", $html);

慕码人2483693

尝试这个模式(?<=<base\s)href="(.*?)"查看演示&nbsp; $html = '<html><head><base href="/" /></head><body></body></html>';&nbsp; $base = 'https://SOME_URL/';&nbsp; res=$html.replace(/(?<=base\s)href="([^"]*)"/,`"${$base}"`)&nbsp; console.log(res)
打开App,查看更多内容
随时随地看视频慕课网APP