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

Hello Monks,

I am trying to do some simple formatting to a text field. I strip the html and want to use my own code to insert a select few html tags.

The way I have it set up now is
# change color s/\[color=/<font color=\"/gi; s/\[\/color\]/<\/font>/gi; # change images s/\[image=/<img src=\"/gi; # change links s/\[link=/<a class=side_nav href=\"/gi; s/\[\/link\]/<\/a>/gi; # Clean up remaining ]'s s/\]/\">/g;
This is poor coding though because any spare ]'s are automatically turned into ">'s.

Is there a way to pull a variable from the center. e.g. Pull var.jpg from [image=var.jpg]

Thanks in advance!!

Replies are listed 'Best First'.
Re: Converting custom mark-up to HTML
by Aragorn (Curate) on Apr 19, 2004 at 17:47 UTC
    It's easier to get the opening and closing tags with the enclosed text in one go instead:
    #!/usr/bin/perl use strict; use warnings; $/ = undef; my $text = <DATA>; $text =~ s!\[color=([^\]]+)\](.*?)\[/color\]!<font color="$1">$2</font +>!gi; $text =~ s!\[image=([^\]]+)\]!<img src="$1">!gi; $text =~ s!\[link=([^\]]+)\](.*?)\[/link\]!<a href="$1">$2</a>!gi; print $text; __DATA__ [color=#0000ff]Blue text[/color] with an image: [image=var.jpg] And a link to Google: [link=http://www.google.com]Google[/link].
    This gives the following output (which I think is what you want):
    <font color="#0000ff">Blue text</font> with an image: <img src="var.jp +g"> And a link to Google: <a href="http://www.google.com">Google</a>.

    Arjen

      Thats exactly what I'm looking for. Having a hard time getting regular expressions. Thank you aragorn!
Re: Converting custom mark-up to HTML
by Art_XIV (Hermit) on Apr 19, 2004 at 17:27 UTC

    Yep! Read up on 'numbered match variables' in perlre. They can be used as in the following:

    use strict; use warnings; while (<DATA>) { s/\[image=([\w\.]+)\]/<img src="$1">/; s/\[color=([\w#]+)\]/<font color="$1">/; s/\[link=([\w:\/\.]+)\]/<a class="my_link" href="$1">/; print; } __DATA__ Hey have a look at this [image=var.jpg] Insert a [color=#99CC99] [link=http://www.perlmonks.net] to the site

    Be warned, though, that what you're attempting to do might not be the best way to achieve what it is that you're trying to achieve. Are there any closing tags available for your bracketed markup?

    Hanlon's Razor - "Never attribute to malice that which can be adequately explained by stupidity"
      Thank you Art_XIV, thats exactly what I was looking for!

      What would be a better way of doing this? I was looking for a way to strip html and still offer some simple formatting.

      I do add closing tags, right after the opening tags.
      s/\[\/color\]/<\/font>/gi; s/\[\/link\]/<\/a>/gi;
Re: Converting custom mark-up to HTML
by Callum (Chaplain) on Apr 19, 2004 at 17:22 UTC