Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations IamaSherpa on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

switching problem...

Status
Not open for further replies.

devilpanther

Programmer
Oct 8, 2004
57
IL
i have a text input that contains
tags, that i want to exchange with <IMG SRC=>.

i tried the next code but it doesn't really work:
Code:
$msg =~ s/\[img](.*)\[/img]/\<IMG SRC=$1\>/g;
why does it work the way to should?
 
Is is possible that you have spaces or other characters hidden in the tags? (e.g. "[ IMG = string ]")
Do you get any error messages?
What does the resultant $msg look like? Unaltered?
Also, you might like to consider altering your ".*" to ".*?" so as to not be too greedy.


Trojan.
 
well i found the problem, but i don't know how to fix it...
the problem is with the < > it creates some sort of weird collition with something, i guess... any ideas?

the output of:
Code:
abc[img]a.bmp[/img]bc[img]b.bmp[/img]
is
Code:
abc<img src=a.bmp]bc[img]b.bmp>[/code[/img]
instead of:
[code]abc<img src=a.bmp>bc<img src=b.bmp>
 
You're using dot-star (which, incidentally, is considered by many to be a bad idea). It's greedy so it matches everything from the first `[' to the last `]'. This will do the trick (note that I've added the `i' flag at the end too, to make it case-insensitive):
Code:
$msg =~ s/\[img]([^\[/img]]*)\]/<IMG SRC=$1>/gi;
 
can you please explain the
Code:
\[img]([^\[/img]]*)\]
because i still don't really understand it...
what is each char do?


thank you.
 
Sure - here it is with comments:
Code:
$msg =~ s/
    \[        # opening square bracket
    IMG=      # followed by the literal string `IMG='
    (         # begin capturing group $1
       [^\]]* # any number of characters that are not a closing square bracket
    )         # close capturing group $1
   \]         # closing square bracket
/<IMG SRC=$1>/xgi;
 
can you also explain,char by char the
Code:
[^\]]*

because that's my real problem...


thank you.
 
It's what's known as a negated character class.

Basically, any characters inside square brackets means that it should match one of any of those characters. In this case, I have a closing square bracket in my character class (which needs the backslash so that it isn't interpreted as being the end of the character class). The caret `^' signifies that it should match the opposite - i.e. any character that is *not* a closing square bracket. The star just means to match zero or more characters that are not square brackets.

If that doesn't explain it sufficiently, you can read up on character classes and negated character classes (with examples) in perlretut.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top