1

Can I replace following regex into one regex in perl

message =~ s/&lt;span&gt;(.*?)&lt;\/span&gt;/<span>$1<\/span>/g;
message =~ s/&lt;em&gt;(.*?)&lt;\/em&gt;/<em>$1<\/em>/g;
message =~ s/&lt;ul&gt;(.*?)&lt;\/ul&gt;/<ul>$1<\/ul>/g;
message =~ s/&lt;ol&gt;(.*?)&lt;\/ol&gt;/<ol>$1<\/ol>/g;

2 Answers 2

3

You can do it like this:

message =~ s#
       &lt;
       (?<tag>span|em|ul|ol)   
       &gt;
       (.*?)
       &lt;
       /
       \k<tag>   
       &gt;
     #
       <$+{tag}>  
       $2    
       </$+{tag}>
     #xg;
Sign up to request clarification or add additional context in comments.

4 Comments

This is a very elegant answer, but it isn't strictly speaking equivalent. Compare the result for encode_entities "<span><em>foo</em></span>". As this answer doesn't recurse, the output would be <span> &lt;em&gt;foo&lt;/em&gt; </span>`.
@amon. Yeah, that is an issue. Nested tags is always going to have problem while combining HTML with Regex.
yes, that's an issue...any solution for Nested tags...I need that for my text conversion...
@manu. Use appropriate html parser. Regex is not the right tool to parse HTML.
1

I'm not sure you need to capture the content between tags. Why not just replace &lt; and &gt; around tag names?

message =~ s#&lt;(/?(?:span|em|[uo]l))&gt;#<$1>#g;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.