Monday 23 March 2009

Looking over texts within specified tags

Сегодня копался в завалах своего и чужого кода с целью почистить и удалить все, чего я не касался долгое время. Нашел на мой взгляд неплохой код собственного производства. Большой нужды в нем нет - писался одноразово, но хорошо документировано и жалко выкидывать. Смысл функции достаточно прост - найти и вытащить текст, окруженный заданным тегом.
#
# htmlLookOver()
# There is extended implementation of the 
# J.E.F.Friedl, Mastering Regular Expressions, p.190 in Russian Edition
#
# @param    string   $string   Looking over html-text
# @param    string   $tagName  Paired tag name
# @param    string   $subRegex The part of the regex, if not specified it 
#                              corresponds to any attributes of the opening tag
#
# @return   array    The list of matching substrings
#
sub htmlLookOver
{
    my ($string, $tagName, $subRegex, ) = (shift, shift, shift);

    return () unless $string && $tagName;

    $subRegex = '[^>]*' unless defined $subRegex;

    my $search = qr/
        <($tagName)          # opening tag
        $subRegex>           # some attrs
        (
            (?:
                (?!<\/?\1>)  # any text between opening and closing tags excluding them
                .
            )*
        )
        <\/\1>               # closing tag
    /sx;

    my @result;
    $string =~ m/$search/;
    do {
        $result[$#result + 1] = $2;
    } while ( $' =~ m/$search/ );

    return @result;
}

No comments:

Post a Comment