In preg_replace_callback, I want to write a conditional branching process with an if statement.

Asked 1 months ago, Updated 1 months ago, 4 views

<?php
$content=<<<'EOD'
<preclass="prettyprint linenums">
<?php
if($hoge=='hoge'){
  echo 'hoge!';
}
<span class="nocode">text</span>
</pre>
?>
EOD;
?>

At the time of displaying the source code such as this on Wordpress, the part of the source code is displayed by substantive reference conversion by htmlspecialchars.
However, I would like to use <span class="nocode">Annotation</span> to include annotations in the source code.
<span class="nocode">Annotation</span> should be displayed without entity reference conversion.
Alternatively, I would like to display lines starting with <span class="nocode"> without entity reference conversion.
Alternatively, htmlspecialchars_decode with lines <spanclass="nocode">~<span> after the $content has been entity-referenced conversion.

Extracting and replacing strings in $content with preg_replace_callback

$content=preg_replace_callback(
  '/<pre(.*?)>(.+?)\<\/pre\>/s',
  function($matchse){
    return html specialchars ($matchese[2], ENT_QUOTES, 'UTF-8');
  },
  $content
  );

$content is var_dump

string(131)"
&lt;?php
if($hoge==&#039;hogeho&#039;){
  echo&#039;hoge&#039;;
}
&span class=&quot;nocode&quot;&nocode&/span&gt;

?>"

and I was able to convert the contents to a physical reference.

If <span class="nocode">Annotation</span> is not in the source code, but only if it is, you do not want to convert only the <span class="nocode">Annotation</span> part.

What should I do in this case?

I look forward to hearing from you.

php

2022-09-30 11:11

1 Answers

callback:

$content=preg_replace_callback(
    '/(<pre.*?>)(.+?)(<span.*?>.*?<\/span>.*)?(<\/pre\>)/s',
    function($matchse){
        $h = $matchese[1];
        $h.=htmlspecialchars($matchese[2], ENT_QUOTES, 'UTF-8');
        $h.=$matchese[3];
        $h.=$matchese[4];
        return$h;
    },
    $content
);

var_dump($content);

annotated input:

<?php
$content=<<<'EOD'
<preclass="prettyprint linenums">
<?php
if($hoge=='hoge'){
  echo 'hoge!';
}
<span class="nocode">text</span>
</pre>
?>
EOD;

annotated output:

string(146)"<preclass="prettyprint linens">
&lt;?php
if($hoge==&#039;hoge&#039;){
  echo&#039;hoge!&#039;
}
<span class="nocode">text</span>
</pre>
?>"

Unnoticed input:

<?php
$content=<<<'EOD'
<preclass="prettyprint linenums">
<?php
if($hoge=='hoge'){
  echo 'hoge!';
}
</pre>
?>
EOD;

Unnotated Output:

string(114)"<preclass="prettyprint linens">
&lt;?php
if($hoge==&#039;hoge&#039;){
  echo&#039;hoge!&#039;
}

</pre>
?>"


2022-09-30 11:11

If you have any answers or tips


© 2022 OneMinuteCode. All rights reserved.