Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to regex character < and > replace like &lt; and &gt; in tag <code> </code>?

Tags:

html

regex

php

I have a string like bellow:

<pre title="language-markup">
    <code>
        <div title="item_content item_view_content" itemprop="articleBody">
            abc
        </div>
    </code>
</pre>

In the <code></code> tag I want to replace all the characters < and > with &lt; and &gt;. How should I do?

Example: <code> &lt; div &gt;<code>.

Please tell me if you have any ideas. Thanks all.

like image 550
Xuân Hiển Ngô Avatar asked Feb 08 '23 07:02

Xuân Hiển Ngô


1 Answers

try below solution:

$textToScan = '<pre title="language-markup">
    <code>
        <div title="item_content item_view_content" itemprop="articleBody">
            abc
        </div>
    </code>
</pre>';


// the regex pattern (case insensitive & multiline
$search = "~<code>(.*?)</code>~is";

// first look for all CODE tags and their content
preg_match_all($search, $textToScan, $matches);
//print_r($matches);

// now replace all the CODE tags and their content with a htmlspecialchars() content
foreach($matches[1] as $match){
    $replace = htmlspecialchars($match);
    // now replace the previously found CODE block
    $textToScan = str_replace($match, $replace, $textToScan);
}

// output result
echo $textToScan;

output:

<pre title="language-markup">
    <code>
        &lt;div title=&quot;item_content item_view_content&quot; itemprop=&quot;articleBody&quot;&gt;
            abc
        &lt;/div&gt;
    </code>
</pre>
like image 95
Chetan Ameta Avatar answered Feb 10 '23 23:02

Chetan Ameta