Reputation:
I have been working on this for whole day but couldn't find a solution in which I can replace substrings in string in php like I have string
'<div>
<h2>this is <span>String</span> found in h2 tag</h2>
<p>Hello World</p>
<h2>this is <span>String</span> found in h2 tag</h2>
<p>Hello Universe</p>
<h2>this is <span>String</span> found in h2 tag</h2>
</div>'
I want to get every string inside h2 and then perform some htmlentity replacement like
$str = 'this is <span>String</span> found in h2 tag';
$sanitized = htmlspecialchars($str,ENT_QUOTES);
and then output complete string but replaced.
How it can be done?
<div>
<h2>this is <span>String</span> found in h2 tag</h2>
<p><b>Hello</b> World</p>
<h3>this is <span>String</span> found in h2 tag</h3>
<p><b>hello</b> Universe</p>
<h2>this is <span>String</span> found in h2 tag</h2>
</div>
Upvotes: 0
Views: 688
Reputation: 20387
You can use preg_replace_callback(). Regular expression for matching <h2>
tags is :
/<h2>(.+?)<\/h2>/
If you would like to match all <hx>
tags instead use the following instead:
/<h([1-6])(.*?)<\/h\1>/
In callback function you can alter the matched string. For example:
$html = <<< EOH
<div>
<h2>this is <span>String</span> found in h2 tag</h2>
<p>Hello World</p>
<h2>this is <span>String</span> found in h2 tag</h2>
<p>Hello Universe</p>
<h2>this is <span>String</span> found in h2 tag</h2>
</div>
EOH;
$html = preg_replace_callback("/<h2>(.+?)<\/h2>/", function($matches) {
/* Convert content of <h2> tags to HTML entities. */
$altered = htmlspecialchars($matches[1], ENT_QUOTES);
/* Put the converted content back inside <h2> tag and return it. */
return str_replace($matches[1], $altered, $matches[0]);
}, $html);
$html = preg_replace_callback("/<p>(.+?)<\/p>/", function($matches) {
/* Make match bold. */
$altered = "<b>" . $matches[1] . "</b>";
/* Put the converted content back inside <p> tag and return it. */
return str_replace($matches[1], $altered, $matches[0]);
}, $html);
print $html;
Output of the above script is:
<div>
<h2>this is <span>String</span> found in h2 tag</h2>
<p><b>Hello World</b></p>
<h2>this is <span>String</span> found in h2 tag</h2>
<p><b>Hello Universe</b></p>
<h2>this is <span>String</span> found in h2 tag</h2>
</div>
Upvotes: 3