我正在開發一個需要解析和操作 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>';
2 回答

翻過高山走不出你
TA貢獻1875條經驗 獲得超3個贊
您的正則表達式 - <base href="(.+)">
, 不匹配,因為后面的部分"(.+)"
是錯誤的。查看源字符串 -<base href="/" />
看到了嗎
?和/
?然后是. >
_
這只是使用正則表達式解析 HTML 不是一個好主意的眾多原因之一。即使沒有那個空格,甚至可能沒有那個,該元素也是完全有效的/
。
但是,如果您 100% 確信該元素的位置base
不會變得太復雜(例如大量嵌套、屬性之間的新行等)。你也許可以通過——/<base[ ]*?href=".+"/i
查看演示
在 PHP 中,為了獲得預期的輸出,你可以這樣做-
$base = 'https://SOME_URL/';
$output = preg_replace('/(<base[ ]*?href=").+(")/', "$1$base$2", $html);

慕碼人2483693
TA貢獻1860條經驗 獲得超9個贊
嘗試這個模式
(?<=<base\s)href="(.*?)"
查看演示
$html = '<html><head><base href="/" /></head><body></body></html>';
$base = 'https://SOME_URL/';
res=$html.replace(/(?<=base\s)href="([^"]*)"/,`"${$base}"`)
console.log(res)
- 2 回答
- 0 關注
- 145 瀏覽
添加回答
舉報
0/150
提交
取消