我正在处理一个需要解析和操作HTML的项目。我需要替换HTML字符串中的"基本Url"。我正试图使用RegEx。我尝试了多种模式,但没有成功。以下是我当前的代码-
<?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>';
您的正则表达式-<base href="(.+)">
不匹配,因为"(.+)"
之后的部分错误。看看源字符串-<base href="/" />
,看到了吗?和CCD_ 7?并且然后CCD_ 8。
这只是用正则表达式解析HTML是个坏主意的众多原因之一。即使没有该空间,甚至可能没有/
,该元素也是完全有效的。
然而,如果你100%肯定这个base
元素的位置不会变得太复杂(例如,大量嵌套、属性之间的新行等(。你可能只需要-/<base[ ]*?href=".+"/i
就可以应付
查看演示
在PHP中,为了获得预期的输出,您可以执行-
$base = 'https://SOME_URL/';
$output = preg_replace('/(<base[ ]*?href=").+(")/', "$1$base$2", $html);
尝试此模式
(?<=<bases)href="(.*?)"
查看演示
$html = '<html><head><base href="/" /></head><body></body></html>';
$base = 'https://SOME_URL/';
res=$html.replace(/(?<=bases)href="([^"]*)"/,`"${$base}"`)
console.log(res)