in reply to Converting multiple spaces to nbsp

A series of spaces preceeded by a space:

s/(?<=\s)(\s+)/'&nbsp;' x length($1)/eg

Update: Added needed parens around the \s+. doh!

Replies are listed 'Best First'.
Re^2: Converting multiple spaces to nbsp
by Smylers (Pilgrim) on Jun 17, 2005 at 13:35 UTC
    s/(?<=\s)(\s+)/'&nbsp;' x length($1)/eg

    You don't need to bother with the length and /e: just substituting one space at a time and letting the /g flag take care of the repetition works fine:

    s/(?<=\s)\s/&nbsp;/g

    Smylers

      oo! That's unexpected! I didn't realize that the previous substitution failed to affect (?<=...). s/(?<=\s)\s/&nbsp;/g had occured to me, but I had dismissed it. ++!

      local $\ = "\n"; local $_ = ' '; s/(?<=\s)\s/&nbsp;/g; print; print($_ eq ' &nbsp;&nbsp;&nbsp;' ? 'correct' : 'wrong'); __END__ &nbsp;&nbsp;&nbsp; correct
        oo! That's unexpected! I didn't realize that the previous substitution failed to affect ...

        If you think about it, it has to be that way: otherwise you could end up subsituting out something that you've just put in there earlier in the same subtitution, and something like s/und/underground/g would get stuck in an infinite loop.

        But it doesn't matter whether using the already-replaced text would enable further substitutions or prevent existing ones; in neither case is it taken into account.

        Smylers