cola
cola

Reputation: 12466

Need a generic php regular expression to do preg_replace

What i tried(it's a static for cpp only)=>

$str1 = "<pre                class="brush:cpp">";

$temp =  preg_replace('/&lt;pre\s+class=&quot;brush:cpp&quot;&gt;/','<pre class="brush:cpp">',$str1);

echo $temp . "\n";

That outputs=>

<pre class="brush:cpp">

But the $str1 can be

"&lt;pre class=&quot;brush:cpp&quot;&gt;"
"&lt;pre class=&quot;brush:java&quot;&gt;"
"&lt;pre class=&quot;brush:php&quot;&gt;"
"&lt;pre class=&quot;brush:python&quot;&gt;"

For those the output should be=>

<pre class="brush:cpp">
<pre class="brush:java">
<pre class="brush:php">
<pre class="brush:python">

Note: I can't use html_entity_decode because the texts will contain other normal string and &lt;br&gt; for <br/>, i don't want to do html_entity_decode for all texts.

I need a generic regular expression to catch cpp/java/php/python. How can i write a generic regular expression to save that part of pattern and keep it as it is in the replace string.

Upvotes: 1

Views: 260

Answers (2)

JRL
JRL

Reputation: 78003

Use

preg_replace('/&lt;pre\s+class=&quot;brush:(.*?)&quot;&gt;/',
             '<pre class="brush:$1">',
             $str1);

Upvotes: 1

nickb
nickb

Reputation: 59699

I believe something like this will work:

preg_replace('/&lt;pre\s+class=&quot;brush:(cpp|java|php|python)&quot;&gt;/','<pre class="brush:$1">',$str1);

It uses a capturing group to capture which ending is present, and it can be one of cpp/java/php/python. The replacement is made with the backreference #1, which will place whichever ending was captured.

Here is an example.

Upvotes: 2

Related Questions