PHP preg_replace: how to replace text between tags?


I have a function doit() that transforms text that way:

I like berries -> I LikE BerrieS.

And I need it to work with html-text to. How can I transform text only between html tags? Don't touch tag name and all tag attributes. E.g. I need:

<p >I LikE BerrieS</p>

but not:

<P ClasS="SupeR GreeN" StylE="HeighT: AutO">I LikE BerrieS</P>

I've tried simple preg_replace() patterns, but nothing worked. I'm new to regexp and need help.

May be preg_match() would be better? Any suggestions? It would be nice to provide working php-code.




$text = '<div>some other text</div> 
<p >i like berries</p>';

//this preg is searching for tags and text inside it
//and then change all first words to upper
$text = preg_replace_callback('#(<.*?>)(.*?)(</.*?>)#', function($matches){

 //this preg is searching for last letters in words and changing it to upper
 $t = preg_replace_callback('#([^ ])( |$)#', function($matches2){
  return strtoupper($matches2[1]) . $matches2[2];
 }, ucwords($matches[2]));
 return $matches[1] . $t . $matches[3];
}, $text);


People are also looking for solutions to the problem: javascript - How to call multiple functions using AJAX


Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.