我在字符串中有一个HTML页面,我需要用%20替换a/ref引用中的所有空格,以便我的解析器理解它。
例如:
<a href="file with spaces.mp3">file with spaces.mp3</a>
需要变成
<a href="file%20with%20spaces.mp3">file with spaces.mp3</a>
一个空格就行了,因为我可以直接用
(.+?)([ *])(.+?)
,然后在$1和$3之间用%20代替
但是对于多个和未知数量的空格,您如何做到这一点,同时仍然有文件名将%20放在中间?
HTML不是一种正则语言,不能使用正则表达式正确解析。而是使用DOM解析器。下面是使用PHP内置的DOMDocument类的解决方案:
$dom = new DOMDocument;
$dom->loadHTML($html);
foreach ($dom->getElementsByTagName('a') as $tag) {
$href = $tag->getAttribute('href');
$href = str_replace(' ', '%20', $href);
$tag->setAttribute('href', $href);
}
$html = $dom->saveHTML();
它基本上遍历所有链接并使用str_replace
更改href
属性。
虽然不建议使用正则表达式,但这里有一个可能适用于您的示例的正则表达式:
(?:<a href="|'G)'S*'K (?=[^">]*")
regex101演示(?:
<a href=" # Match <a href=" literally
|
'G # Or start the match from the previous end-match
)
'S* # Match any non-space characters
'K # Reset the match so only the following matches are replaced
(?=[^">]*") # Ensure that the matching part is still within the href link
上面的正则表达式也可能在某些边缘情况下中断,所以我建议使用DOMDocument,就像Amal的优秀答案一样,它更健壮。