preg_replace() 帮助将 {$variable} 转换为 PHP echo 变量语句


preg_replace() help to convert {$variable} to php echo variable statement

我正在研究小型模板类。我需要帮助将模板文件中写入的 {$variable} 转换为

喜欢:

<html>
   <body>
      <p> Hey Welcome {$username} </p> 
   </body>
</html>

要转换为

    <html>
   <body>
      <p> Hey Welcome <?php echo $username ?> </p> 
   </body>
</html>

就像变量用户名一样,可以有任意长度的任何变量。我只想将其转换为php echo语句。

我认为使用 preg_replace(( 是可能的,但不知道如何。

这是

怎么回事?

$string = 'Hello {$username}, how are you?';
$new_string = preg_replace('/'{('$[a-zA-Z_'x7f-'xff][a-zA-Z0-9_'x7f-'xff]*)'}/', '<?php echo ''1; ?>', $string);
echo $new_string;

这给出了这个:

Hello <?php echo $username; ?>, how are you?

我从 php 手册中借用了这个表达式。

变量名称遵循与 PHP 中其他标签相同的规则。一个有效的 变量名称以字母或下划线开头,后跟任意 字母、数字或下划线的数量。作为正则表达式, 可以这样表示:">[a-zA-Z_''x7f-''xff][a-zA-Z0-9_''x7f-''xff]*'

所以理论上它应该匹配任何有效的变量。

preg_replace('/'{'$username'}/', '<?php echo $username; ?>', $text);

或一般:

preg_replace('/'{'$([^'}]+)'}/', '<?php echo $$1; ?>', $text);

例如:您有应用程序文件夹结构:

  • 应用程序/视图/索引模板
  • 应用/控制器/索引.php
  • 应用/索引.php

其中"应用程序"文件夹是网络根目录

因此,文件"app/view/index.template"包含:

<html>
   <body>
      <p> Hey Welcome {$username} </p> 
   </body>
</html>

"app/controller/index.php"包含以下内容:

<?php
    $username = 'My Hero';
    $content = file_get_contents(__DIR__ . '../view/index.template');
    if ($content) {
        echo str_replace('{$username}', $username, $content);
    } else { echo 'Sorry, file not found...';}

"app/index.php"包含以下内容:

<?php
    include __DIR__ . '/controller/index.php';

类似的东西...