1

我想在 html 文本中使用标记样式的注释来替换 text/html 的部分,具体取决于使用 PHP 的变量名。如果不使用嵌套标签,替换本身就可以完美地工作。
但是如果有嵌套的标签,只有外面的标签会被替换。

我的正则表达式是这个:

\[\@if(not)?:([a-zA-Z0-9]+)(?:=(.*?))?\].*?\[\@endif:\2\]

您可以在此处查看此正则表达式以及要解析的示例内容:
https ://regex101.com/r/rE3fL1/2

我读过(?R) 但无法让它工作。
我尝试用.*?中间替换,(.*?|(?R))但这甚至没有改变任何东西。

如何更改正则表达式以捕获嵌套标签?

代码:($this->output访问文本)

public function output($dbAccess = true) {
        // only translate when dbaccess is granted
        if ($dbAccess) 
            $this->localize();

        // insert values into template
        foreach ( $this->values as $key => $value ) {
            $tagToReplace = "[@$key]";
            $this->output = str_replace ( $tagToReplace, $value, $this->output );
        }

        // gather conditional content sections from output
        $condis = array();
        $conmatches = array ();
        preg_match_all ( '/\[\@if(not)?:([a-zA-Z0-9]+)(?:=(.*?))?\].*?\[\@endif:\2\]/s', $this->output, $conmatches );
        if (count($conmatches) > 0) {
            $c = $conmatches[0];
//          if (count($c) > 0)
//              echo "found " . count($c[0]) . " conditional tpl statement matches!";
            for ($i=0; $i<count($c); $i++) {
                $text = $c[$i];
                $not = $conmatches[1][$i];
                $name = $conmatches[2][$i];
                $value = $conmatches[3][$i];
                $condis[] = new ConditionalContent($text, $not, $name, $value);
            }

            // substitute conditional content sections
            foreach ($condis as $cc) {
                // convenience and readability vars!
                $varname = $cc->name();
                $vals = &$this->values;
                $value = $cc->value();

                // if condition is bound to value of variable and not just existence
                if ($value != "") {
                    // del if name == exists(value)
                    if ($cc->not() && isset($vals[$varname])) {
                        if ($vals[$varname] == $value) {
                            $this->delContent($cc->content());
                        }
                    }
                    // del if not exists(value) or value != name
                    else {
                        if (!isset($vals[$varname]) || $vals[$varname] != $value) {
                            $this->delContent($cc->content());
                        }
                    }
                }
                else {
                    if (    isset($vals[$varname]) && $cc->not() || 
                            !isset($vals[$varname]) && !$cc->not()) {
                        $this->delContent($cc->content());
                    }
                }
            }

            // delete all left over if(not) and endif statements
            $this->output = preg_replace('/\[@(?:if(?:not){0,1}|endif):[a-zA-Z0-9]+(=.*?)?\]/', '', $this->output);
        }
        //else { echo "found no conditional tpl statements"; }

        return $this->output;
    }
4

0 回答 0