Published:
August 02, 2012Replace any text from html text by tag name in php
function replace_tag_text($tagName,$subjectStr,$replaceStr) {
$tagName = preg_quote($tagName);
preg_match_all(‘{<‘.$tagName.'[^>]*>(.*?)</’.$tagName.’>}’,$subjectStr,$matches,PREG_PATTERN_ORDER);
$result = str_replace($matches[1],$replaceStr,$subjectStr);
return $result;
}
Usage :
Say for Example
$ActualStr : ‘<div><span style=”margin: 0px 0px 0px 0px; width: 540px;”>something</span><p style=”float: right; margin: -240px 0 0; width: 200px;”>This is the actual String</p></div>’;
$StrToReplaceWith = ‘This is the replaces str’;
Now you want to replace all the text inside the <div> tags from $ActualStr with $StrToReplaceWith
Then you can do as below:
$replacedStr = replace_tag_text(‘div’,$ActualStr,$StrToReplaceWith);
Result : <div>This is the replaces str</div>
Enjoy 🙂