首先給出幾個(gè)問題。
將html代碼中的js內(nèi)容過濾掉。
將html代碼中table標(biāo)簽中間的內(nèi)容(<table>內(nèi)容</table>)前后加上特殊字符#。
取出img標(biāo)簽alt屬性的值。
html代碼如下:
<html>
<head>
<title>test</title>
</head>
<body>
<script type="text/javascript">
data = 'test data';
</script>
<p><img src="http://test.com/1.jpg" alt="this's a description."></p>
<table>....</table>
<p><img src='http://test.com/2.jpg' alt='other'></p>
<script>
console.log('statics');
</script>
</body>
</html>
第一個(gè)問題,很容易寫出下面代碼:
$html = preg_replace('~<script.*>.+</script>~U', '', $html);
但執(zhí)行的時(shí)候發(fā)現(xiàn)并沒有過濾掉js代碼。
原因是點(diǎn)號(hào)(.)元字符匹配除換行符以外的任意字符。js代碼是多行的,所以用點(diǎn)號(hào)無法匹配,這個(gè)坑很淺,我卻掉進(jìn)去了。
解決方法:使用模式修飾符s,此修飾符可以讓點(diǎn)號(hào)匹配換行符。
$html = preg_replace('~<script.*>.+</script>~Us', '', $html);
執(zhí)行結(jié)果:

第二問題,可以使用php的preg_replace_callback函數(shù)。
$html = preg_replace_callback(
'~<table>(.+)</table>~Us',
function ($matches) {
return '#' . $matches[1] . '#';
},
$html);
第三個(gè)問題:
preg_match_all('~<img.*alt=[\'"](.+)[\'"]~U', $html, $matches);
執(zhí)行結(jié)果:

發(fā)現(xiàn)第一個(gè)匹配出錯(cuò)。由于alt屬性值可能由雙引號(hào)或單引號(hào)包括的,所以在正則中使用[\’”],但如果alt屬性值中有單引號(hào)或雙引號(hào)就會(huì)匹配不全,此時(shí)可以使用反向引用來解決,好吧,我竟然忘了反向引用。
preg_match_all('~<img.*alt=([\'"])(.+)\1~U', $html, $matches);
