这将适用于不应该使用正则表达式来解析 xml/html 等的警告。
它总是更容易捕获简单的样本,然后在回调中对它们进行子处理。
在这种情况下捕获 ([alphabet"*`,]+),然后去掉不需要的字符,然后进行比较。
Perl 示例,概念与 Perl/PHP/C# 等相同...
$sample = '
<hw>Al"pha*bet</hw>
<hw>Al"pha*be`t</hw>
<hw>alphabet</hw>
<hw>al*pha*bet</hw>
<hw>al"pha"b"et</hw>
';
$specialword = 'alphabet';
$uc_specialword = uc( $specialword );
while ($sample =~ m{<([A-Za-z_:][\w:.-]*)(?:\s+(?:".*?"|\'.*?\'|[^>]*?)+)?\s*(?<!/)>([$specialword"*`,]+)</\1\s*>}isg)
{
($matchstr, $checkstr) = ($&, $2);
$checkstr =~ s/["*`,]//g;
if (uc($checkstr) eq $uc_specialword) {
print "Found '$checkstr' in '$matchstr'\n";
}
}
扩展正则表达式:
m{ # Regex delim
< # Open tag
([A-Za-z_:][\w:.-]*) # Capture 1, the tag name
(?:\s+(?:".*?"|\'.*?\'|[^>]*?)+)?\s* # optional attr/val pairs
(?<!/)
>
([alphabet"*`,]+) # Capture 2, class of special characters allowed, 'alphabet' plus "*`,
</\1\s*> # Close tag, backref to tag name (group 1)
}xisg # Regex delim. Options: expanded, case insensitive, single line, global
输出:
Found 'Alphabet' in '<hw>Al"pha*bet</hw>'
Found 'Alphabet' in '<hw>Al"pha*be`t</hw>'
Found 'alphabet' in '<hw>alphabet</hw>'
Found 'alphabet' in '<hw>al*pha*bet</hw>'
Found 'alphabet' in '<hw>al"pha"b"et</hw>'
PHP 示例
preg_match()
可以在这里找到使用http://www.ideone.com/8EBpx
<?php
$sample = '
<hw>Al"pha*bet</hw>
<hw>Al"pha*be`t</hw>
<hw>alphabet</hw>
<hw>al*pha*bet</hw>
<hw>al"pha"b"et</hw>
';
$specialword = 'alphabet';
$uc_specialword = strtoupper( $specialword );
$regex = '~<([A-Za-z_:][\w:.-]*)(?:\s+(?:".*?"|\'.*?\'|[^>]*?)+)?\s*(?<!/)>([' . $specialword. '"*`,]+)</\1\s*>~xis';
$pos = 0;
while ( preg_match($regex, $sample, $matches, PREG_OFFSET_CAPTURE, $pos) )
{
$matchstr = $matches[0][0];
$checkstr = $matches[2][0];
$checkstr = preg_replace( '/[" * `,]/', "", $checkstr);
if ( strtoupper( $checkstr ) == $uc_specialword )
print "Found '$checkstr' in '$matchstr'\n";
$pos = $matches[0][1] + strlen( $matchstr );
}
?>
preg_match_all()
可以在这里找到使用http://www.ideone.com/C6HeT
<?php
$sample = '
<hw>Al"pha*bet</hw>
<hw>Al"pha*be`t</hw>
<hw>alphabet</hw>
<hw>al*pha*bet</hw>
<hw>al"pha"b"et</hw>
';
$specialword = 'alphabet';
$uc_specialword = strtoupper( $specialword );
$regex = '~<([A-Za-z_:][\w:.-]*)(?:\s+(?:".*?"|\'.*?\'|[^>]*?)+)?\s*(?<!/)>([' . $specialword. '"*`,]+)</\1\s*>~xis';
preg_match_all($regex, $sample, $matches, PREG_SET_ORDER);
foreach ($matches as $match)
{
$matchstr = $match[0];
$checkstr = $match[2];
$checkstr = preg_replace( '/[" * `,]/', "", $checkstr);
if ( strtoupper( $checkstr ) == $uc_specialword )
print "Found '$checkstr' in '$matchstr'\n";
}
?>