我想将代码字符串替换为PHP文本中的预代码


I would like to replace code strings to pre code in text in PHP

我想将代码字符串替换为文本中的预代码。

例如:

@PHP +++
public function example()
{
    echo "Hello World.";
}
+++
@JS +++
alert("Hello World!");
+++

替换为:

<pre class="PHP">
public function example()
{
    echo "Hello World.";
}
</pre>
<pre class="JS">
alert("Hello World!");
</pre>

my condition now:

public function decorate( $str = "" )
{
    $str = htmlspecialchars($str, ENT_QUOTES, "utf-8", false);
    $str = str_replace("'t","&nbsp;&nbsp;&nbsp;&nbsp;",$str);
    $str = str_replace(" ","&nbsp;",$str);
    $str = preg_replace("/@(.+?)'+'+'+(.*)'+'+'+/is", "<pre class='$1'>$2</pre>", $str);
    $str = nl2br($str);
    return $str;
}

问题1:从"nl2br"函数工作的"pre"的换行重复。
问题2:regexp /@(.+?)'+'+'+(.*)'+'+'+/is不正确。

你知道正确的方法吗?

使用

:

$replaced = preg_replace('~(?sm)^@('S+)[ ]*('+'+'+)(.*?)'2~',
                         '<pre class="$1">$3</pre>',
                         $yourstring);

当您检查替换时,确保通过htmlentities查看它,否则标记将不会显示。例如:echo htmlentities($replaced);

  • (?sm)激活DOTALL和多行模式,允许点匹配换行,^匹配换行
  • ^锚断言我们位于字符串
  • 的开头
  • @匹配文字@
  • ('S+)捕获任何非空白字符到组1
  • [ ]*可选择匹配空格
  • ('+'+'+)匹配三个加号并将它们捕获到组2(所以我们不必再次输入)
  • (.*?)惰性匹配并捕获到第3组中不超过…的所有字符
  • '2反向引用,即+++
  • 我们将其替换为<pre class="$1">$3</pre>,其中$1代表第1组,以此类推。

<pre class="PHP">
public function example()
{
    echo "Hello World.";
}
</pre>
<pre class="JS">
alert("Hello World!");
</pre>

你的php代码应该是,

<?php
$string = <<<EOT
@PHP +++
public function example()
{
    echo "Hello World.";
}
+++
@JS +++
alert("Hello World!");
+++
EOT;
$regex = array('~@('w+)'s*'+'+'+~','~'+'+'+~');
$replace = array(
  '<pre class="'1">',
  '</pre>'
);
$result = preg_replace($regex,$replace,$string);
echo $result;
?>
输出:

<pre class="PHP">
public function example()
{
    echo "Hello World.";
}
</pre>
<pre class="JS">
alert("Hello World!");
</pre>

演示

解释:

  • @('w+)'s*'+'+'+捕获后跟@符号的一个或多个单词字符,该符号以+++结尾。将对应的整条线替换为<pre class="'1">'1表示捕获的第一组。
  • ~'+'+'+~只包含三个+++符号的行被</pre>代替。