Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

Task = To replace all leading spaces after <br> to &nbsp;

Example below

Input -->Some Text <br>      ABCD</br> Some Thing Else<--

Output-->SomeText<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;ABCD</br> Some Thing Else<--

I have written the following code to do the same

$excel_br="<br>"; $line ="Some Text <br>      ABCD</br> Some Thing Else" $line =~ s/$excel_br /$excel_br&nbsp;/g ; 1 while ($line =~ s/($excel_br(&nbsp;)+)/$1&nbsp;/g ) ;

I was wondering if the same is possible with a single regex without the while loop ?

Replies are listed 'Best First'.
Re: Replace leading Spaces after a tag
by ikegami (Patriarch) on Oct 09, 2010 at 07:07 UTC
    s/<br>\K( +)/"&nbsp;" x length($1)/eg;
Re: Replace leading Spaces after a tag
by kcott (Archbishop) on Oct 09, 2010 at 07:12 UTC
    $ perl -wE 'my $x = q{Some Text <br> ABCD </br>...}; $x =~ s/<br> +(\s*)/q{<br>} . q{&nbsp;} x length($1)/eg; say $x' Some Text <br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;ABCD </br>...

    Minor side issue: </br> isn't a valid HTML tag.

    -- Ken

Re: Replace leading Spaces after a tag
by ww (Archbishop) on Oct 09, 2010 at 11:31 UTC
Re: Replace leading Spaces after a tag
by Your Mother (Archbishop) on Oct 09, 2010 at 15:58 UTC

    You might also consider stripping the <br>s altogether (update: for newlines, I mean) and changing the CSS white-space property in the parent to pre or pre-wrap. I know HTML is a sloppy business but &nbsp;, much like <br> itself, is a hacky solution for getting layout the way it should be.