FOO...">

Regex Replace with Backreference changed by functions

I want to replace the class with div text as follows:
This is: <div class="grid-flags" >FOO</div>

It becomes: <div class="iconFoo" ></div>

Thus, the class changes to โ€œiconโ€. ucfirst (strtolower (FOO)) and the text is deleted

HTML testing

 <div class="grid-flags" >FOO</div> 

template

 '/class=\"grid-flags\" \>(FOO|BAR|BAZ)/e' 

Replacement

 'class="icon'.ucfirst(strtolower($1).'"' 

This is one example of replacing a string that I tried from seemingly hundreds. I read that the / e modifier evaluates the PHP code, but I donโ€™t understand how it works in my case, because I need double quotes around the class name, so I'm lost as to how to do this.

I tried options on backref, for example. strtolower ('$ 1'), strtolower ('\ 1'), strtolower ('{$ 1}')

I tried single and double quotes and various screens, etc., and nothing worked.

I even tried preg_replace_callback () with no luck

 function callback($matches){ return 'class="icon"'.ucfirst(strtolower($matches[0])).'"'; } 
+4
source share
3 answers

It was hard for me to try to understand what you had in mind, but I think you want something like this:

 preg_replace('/class="grid-flags" \>(FOO|BAR|BAZ)/e', '\'class="icon\'.ucfirst(strtolower("$1")).\'">\'', $text); 

Output for entering your example:

 <div class="iconFoo"></div> 

If this is not what you want, could you give us some examples of inputs and outputs?

And I have to agree that this would be easier with an HTML parser.

+3
source

Instead of using the e (valuate) option, you can use preg_replace_callback () .

 $text = '<div class="grid-flags" >FOO</div>'; $pattern = '/class="grid-flags" >(FOO|BAR|BAZ)/'; $myCB = function($cap) { return 'class="icon'.ucfirst($cap[1]).'" >'; }; echo preg_replace_callback($pattern, $myCB, $text); 

But instead of using regular expressions, you can consider a more suitable parser for html, for example simple_html_dom or php DOM extension .

+2
source

It works for me

 $html = '<div class="grid-flags" >FOO</div>'; echo preg_replace_callback( '/class *= *\"grid-flags\" *\>(FOO|BAR|BAZ)/' , create_function( '$matches', 'return \'class="icon\' . ucfirst(strtolower($matches[1])) .\'">\'.$matches[1];' ) , $html ); 

Just be aware of the problems with parsing HTML with regex .

0
source

Source: https://habr.com/ru/post/1301860/


All Articles