2

So I need to re-write some old code that I found on a library.

    $text = preg_replace("/(<\/?)(\w+)([^>]*>)/e",
                         "'\\1'.strtolower('\\2').'\\3'", $text);

    $text = preg_replace("/<br[ \/]*>\s*/","\n",$text);
    $text = preg_replace("/(^[\r\n]*|[\r\n]+)[\s\t]*[\r\n]+/", "\n",
                         $text);

And for the first one I have tried like this:

 $text = preg_replace_callback(
   "/(<\/?)(\w+)([^>]*>)/",
   function($subs) {
       return strtolower($subs[0]);
   },
   $text);

I'm a bit confused b/c I don't understand this part: "'\\1'.strtolower('\\2').'\\3'" so I'm not sure what should I replace it with.

As far as I understand the first line looks for tags, and makes them lowercase in case I have data like

<B>FOO</B>

Can you guys help me out here with a clarification, and If my code is done properly?

1 Answer 1

1

The $subs is an array that contains the whole value in the first item and captured texts in the subsequent items. So, Group 1 is in $subs[1], Group 2 value is in $subs[2], etc. The $subs[0] contains the whole match value, and you applied strtolower to it, but the original code left the Group 3 value (captured with ([^>]*>) that may also contain uppercase letters) intact.

Use

$text = preg_replace_callback("~(</?)(\w+)([^>]*>)~", function($subs) {
    return $subs[1] . strtolower($subs[2]) . $subs[3]; 
 }, $text);

See the PHP demo.

Sign up to request clarification or add additional context in comments.

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.