[Dresden-pm] Reguläre Ausdrücke - Suchen und Ersetzen von Worten

Aristotle Pagaltzis pagaltzis at gmx.de
Di Aug 12 07:16:46 PDT 2008


* Falk Herrmann <falk.herrmann at bike24.net> [2008-08-12 10:35]:
> Mal schauen, was noch kommt.

    my @keywords = ( 'affe', 'hund', 'affe klettert', 'hund rennt' );
    my $text = 'Ein Affe klettert, weil er ein Affe ist. Ein Hund rennt, weil er ein Hund ist.';

    my %insertion;
    for my $kw ( @keywords ) {
        my ( $rx ) = map qr/$_/i, quotemeta $kw;
        while ( $text =~ /$rx/g ) {
            push    @{ $insertion{ $-[0] } }, '<a href="#">';
            unshift @{ $insertion{ $+[0] } }, '</a>';
        }
    }

    my $result    = '';
    my $last_offs = 0;
    for my $offset ( sort { $a <=> $b } keys %insertion ) {
        $result
            .= substr( $text, $last_offs, $offset - $last_offs )
            .  join( '', @{ $insertion{ $offset } } );

        $last_offs = $offset;
    }

    $result .= substr( $text, $last_offs );

Ich habe leider keine Zeit, das zu erklären, weil mein Flug zur
YAPC::EU gleich geht.

-- 
*AUTOLOAD=*_;sub _{s/(.*)::(.*)/print$2,(",$\/"," ")[defined wantarray]/e;$1}
&Just->another->Perl->hack;
#Aristoteles Pagaltzis // <http://plasmasturm.org/>


Mehr Informationen über die Mailingliste Dresden-pm