Reputation: 12466
What i tried(it's a static for cpp only)=>
$str1 = "<pre class="brush:cpp">";
$temp = preg_replace('/<pre\s+class="brush:cpp">/','<pre class="brush:cpp">',$str1);
echo $temp . "\n";
That outputs=>
<pre class="brush:cpp">
But the $str1 can be
"<pre class="brush:cpp">"
"<pre class="brush:java">"
"<pre class="brush:php">"
"<pre class="brush:python">"
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 <br>
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
Reputation: 78003
Use
preg_replace('/<pre\s+class="brush:(.*?)">/',
'<pre class="brush:$1">',
$str1);
Upvotes: 1
Reputation: 59699
I believe something like this will work:
preg_replace('/<pre\s+class="brush:(cpp|java|php|python)">/','<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