Ali Hassan
Ali Hassan

Reputation: 75

get data from between two stings in PHP

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('<', '&lt;', $sub_str);

I have tried using explode() but was unable to get all the <code> tags from the string.

Upvotes: 0

Views: 39

Answers (1)

Booboo
Booboo

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('<', '&lt;', $matches[0]);
        // to replace '>' also:
        //return str_replace('>', '&gt;', str_replace('<', '&lt;',$matches[0]));
    },
    $str
);
echo $str;

Prints:

Loreum Ipsum Dolor Sit Amet <code>Some HTML Code like &lt;h1>Head&lt;/h1></code>. Loreum Ipsum <code>Some Code</code> Dolor Sit Amet.

See Regex Demo

  1. (s) Sets single-line mode so that . matches the newline character.
  2. (?<=<code>) A lookbehind assertion stating that the preceding characters match <code>.
  3. .*? A non-greedy match matching 0 or more characters until ...
  4. (?=</code>) A lookahead assertion stating that the following characters match <code>.

PHP Demo

Upvotes: 1

Related Questions