假设网页内容如下:
{eyou:arclist orderby='sort_order' row='8' subday='30' titlelen='42'}
<a href="{$field.arcurl}">{$field.title}</a>
{/eyou:arclist}
{eyou:sql sql='xxxxxxxx'}
<span>不支持sql标签</span>
{/eyou:sql }
{eyou:arclist orderby='sort_order' row='8' subday='30' titlelen='42'}
<div>{$field.title}</div>
<div>{$field.typename}</div>
{/eyou:arclist}
匹配每一个{eyou:arclist}和{/eyou:arclist}之间的内容,暂时不考虑arclist会嵌套的问题。
首先想到的正则是这样写的:
preg_match_all( '/{eyou:sql([^\}]*)}(.*?){\/eyou:sql}/i', $string, $matches );
echo "<pre>";
print_r( $matches);
echo '</pre>';
但运行不了,经网上搜寻资料后改成如下写法后即可:
preg_match_all( '/{eyou:sql([^\}]*)}([\s\S]*?){\/eyou:sql}/i', $string, $matches );
echo "<pre>";
print_r( $matches);
echo '</pre>';
理由很简单,回头复习一上正则表达示中【.】、【\s】和【\S】就知道了,当([\s\S]*)结合在一起时,表示比(.*)包含的字符还要多久,可以说是包含任意字符。
【.】匹配除 "\n" 之外的任何单个字符。要匹配包括 '\n' 在内的任何字符,请使用象 '[.\n]' 的模式。
【\s】匹配任何空白字符,包括空格、制表符、换页符等等。等价于 [ \f\n\r\t\v]。
【\S】匹配任何非空白字符。等价于 [^ \f\n\r\t\v]。
附上html普通标签示例:
<table>
<tr>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
</tr>
</table>
匹配的是每一个<tr></tr>之间的内容(当然tr里面有很多内容,这里没有列出来),暂时不考虑tr会嵌套的问题。
preg_match_all( '/<tr[^>]*([\s\S]*?)<\/tr>/i', $string, $matches );
echo "<pre>";
print_r( $matches);
echo '</pre>';
|