in reply to Re: Print N characters per line in Cgi Script with Html Tags
in thread Print N characters per line in Cgi Script with Html Tags

this does not work; lines end up being of different length and the colours disappear. To simplify my task to the minimum, imagine, still inside a CGI script you have 2 strings:
my $a: "ABCDEFGHI" my $b: "<b>ABC</b>DEFGHI"
I want to print this 2 strings with 4 characters per line and in the second string ABC has to be in bold; If I use my method, or your method, this is what I get:
$a: ABCD EFGH I $b: <b>A BC</ b>DE FGHI
I want the bold tags ingored in the characters counts: So:
$a: ABCD EFGH I $b: <b>ABC</b>D EFGH I
Also as I said, when I try your code it also does something with the coloured tags I used; Note: in this example I am using bold tag to make it shorter, in my scrip I am using a span class as shown. I hope it is more clear. I do not know in advance where the position it is: i need an universal solution which can print something with the same number of characters per line, basically ignoring the tags in the counts.

Replies are listed 'Best First'.
Re^3: Print N characters per line in Cgi Script with Html Tags
by hippo (Archbishop) on Jun 13, 2017 at 16:11 UTC

    I see. If you have tags already in your data and want to skip over them then the best plan is to use a proper HTML parser.

    If you cannot (or will not) use a parser then a crude plan B which works for your supplied dataset is:

    #!/usr/bin/env perl use strict; use warnings; use Test::More; my @set = ( { in => 'ABCDEFGHI', want => "ABCD\nEFGH\nI\n" }, { in => '<b>ABC</b>DEFGHI', want => "<b>ABC</b>D\nEFGH\nI\n" }, ); plan tests => scalar @set; my $len = 4; for my $x (@set) { my $i = 0; my $out = ''; my $intag = 0; for my $c (split (//, $x->{in})) { $out .= $c; $intag++ if $c eq '<'; $intag-- if $c eq '>'; next if $intag || $c eq '>'; $i++; $out .= "\n" unless $i % $len; } $out .= "\n"; is ($out, $x->{want}); }

    This isn't robust (and is rather C-ish for my taste) but it serves to illustrate this approach in general terms. Have fun with it.

    Update: edited source for improved generality.