views:

174

answers:

3

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

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

So the class is changed to "icon". ucfirst(strtolower(FOO)) and the text is removed

Test HTML

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

Pattern

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

Replacement

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

This is one example of a replacement string I've tried out of 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 the double quotes around the class name so I'm lost as to which way to do this.

I tried variations on the backref eg. strtolower('$1'), strtolower('\1'), strtolower('{$1}')

I've tried single and double quotes and various escaping etc and nothing has worked yet.

I even tried preg_replace_callback() with no luck

function callback($matches){
    return 'class="icon"'.ucfirst(strtolower($matches[0])).'"';
}
+2  A: 

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 might want to consider a more suitable parser for html like simple_html_dom or php's DOM extension.

VolkerK
Good suggestions. Thanks!
Jesse
A: 

This 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 of parsing HTML with regex.

Peter Bailey
I am now aware and I thank you...
Jesse
+1  A: 

It was difficult for me to try to work out what you meant, 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 your example input:

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

If this isn't what you want, could you please give us some example inputs and outputs?

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

Mark Byers
Thanks everyone for your answers over the weekend. This was the original way I was trying to do it and the most concise, so I made this the accepted answer, but you all made great points.
Jesse