【问题标题】:PHP preg_replace string within variablesPHP preg_replace 变量中的字符串
【发布时间】:2018-06-18 11:14:51
【问题描述】:

我正在使用 PHP 7.2.4,我想做一个模板引擎项目, 我尝试使用 preg_replace 更改字符串中的变量, 代码在这里:

<?php
$lang = array(
    'hello' => 'Hello {$username}',
    'error_info' => 'Error Information : {$message}',
    'admin_denied' => '{$current_user} are not Administrator',
);

$username = 'Guest';
$current_user = 'Empty';
$message = 'You are not member !';

$new_string = preg_replace_callback('/\{(\$[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*)\}/', 'test', $string);

function test($matches)
{
    return '<?php echo '.$matches[1].'; ?>';
}

echo $new_string;

但它只是告诉我

Hello , how are you?

它会自动删除变量...

更新: 这里是 var_dump:

D:\Wamp\www\t.php:5:string 'Hello <?php echo $username; ?>, how are you?' (length=44)

【问题讨论】:

  • preg_replace_callback
  • This is an example how you can do it。定义一个关联数组而不是单独的变量,并用它来替换匹配项。
  • @WiktorStribiżew 是的!非常感谢~

标签: php preg-replace template-engine


【解决方案1】:

您可以使用键(您的变量)和值(它们的值)创建一个关联数组,然后捕获$ 之后的变量部分,并使用它来检查preg_replace_callback 回调函数是否有键命名为找到的捕获。如果是,则替换为对应的值,否则,替换为匹配项将其放回找到的位置。

这是example code in PHP

$values = array('username'=>'AAAAAA', 'lastname'=>'Smith');
$string = 'Hello {$username}, how are you?';
$new_string = preg_replace_callback('/\{\$([a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*)}/', function($m) use ($values) {
        return 'Hello <?php echo ' . (!empty($values[$m[1]]) ? $values[$m[1]] : $m[0]) . '; ?>';
    }, $string);

var_dump($new_string);

输出:

string(47) "Hello Hello <?php echo AAAAAA; ?>, how are you?"

注意模式字符,我把括号移到$之后:

\{\$([a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*)}
    ^                                        ^

其实你甚至可以把它缩短成

\{\$([a-zA-Z_\x7f-\xff][\w\x7f-\xff]*)}
                        ^^

【讨论】:

    【解决方案2】:

    你想要这样的东西吗?

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

    结果是:

    Hello AAAAAA, how are you?
    

    更简单的方法是写

    <?php
    $username = 'AAAAAA';
    $string = 'Hello '.$username.', how are you?';
    

    【讨论】:

    • 不行,我想做一个模板引擎类,变量的名字有时会改变,所以我需要让它可以是Hello &lt;?php echo $username; ?&gt;, how are you?
    【解决方案3】:

    我喜欢保持简单,所以我会使用 str_replace,因为它还会更改所有可能在您前进时派上用场的实例。

    $string = 'Hello {$username}, how are you?';
    $username = 'AAAAAA';
    echo str_replace('{$username}',$username,$string);
    

    【讨论】:

    • 我在我的模板引擎项目中使用它,变量太多了,用str_replace函数写所有变量
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-16
    相关资源
    最近更新 更多