Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
475 views
in Technique[技术] by (71.8m points)

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 class="super green" style="height: auto">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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
$text = '<div>some other text</div> 
<p class="super green" style="height: auto">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);

var_dump($text);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...