Reputation: 75
I have the following String
$str = "Loreum Ipsum Dolor Sit Amet <code>Some HTML Code like <h1>Head</h1></code>. Loreum Ipsum <code>Some Code</code> Dolor Sit Amet."
What I need is to get the value from inside all the code tags and apply a PHP function of str_replace()
to that data and join the string back.
str_replace('<', '<', $sub_str);
I have tried using explode()
but was unable to get all the <code>
tags from the string.
Upvotes: 0
Views: 39
Reputation: 44053
You do not need to pull out the string within <code></code>
tags, replace text and join anything back. It can all be done using preg_replace_callback
:
<?php
$str = "Loreum Ipsum Dolor Sit Amet <code>Some HTML Code like <h1>Head</h1></code>. Loreum Ipsum <code>Some Code</code> Dolor Sit Amet.";
$str = preg_replace_callback(
'|(?s)(?<=<code>).*?(?=</code>)|',
function ($matches) {
return str_replace('<', '<', $matches[0]);
// to replace '>' also:
//return str_replace('>', '>', str_replace('<', '<',$matches[0]));
},
$str
);
echo $str;
Prints:
Loreum Ipsum Dolor Sit Amet <code>Some HTML Code like <h1>Head</h1></code>. Loreum Ipsum <code>Some Code</code> Dolor Sit Amet.
(s)
Sets single-line mode so that .
matches the newline character.(?<=<code>)
A lookbehind assertion stating that the preceding characters match <code>
..*?
A non-greedy match matching 0 or more characters until ...(?=</code>)
A lookahead assertion stating that the following characters match <code>
.Upvotes: 1