【问题标题】:Check string to find variables inside (PHP)检查字符串以查找内部变量(PHP)
【发布时间】:2013-07-26 03:50:02
【问题描述】:

我需要读取一个字符串来查找变量(标签)并将其替换为存储的值。 我使用 %(百分比)来识别标签。输入应该接受一些标签,如 %color% 和 %animal%,所以使用 PHP 我需要插入真正的字符串......用代码更好地解释:

// We have some strings stored
$color = 'white';
$animal = 'cat';

用户应该在文本区域中使用 %color%、%animal% 或不使用任何内容来显示他想要的变量。

// The user text was stored by the $text
$text = "The quick %color% fox jumps over the lazy %animal%.";

$text 的 %color% 和 %animal% 应替换为 $color 和 $animal 值。但是,我该怎么做呢?最终输出应该是

<p>The quick white fox jumps over the lazy cat.</p>

WordPress 允许用户在“永久链接”选项中执行此操作,因此用户可以设置,例如,以下结构:

http://localhost/site/%category%/%postname%/

【问题讨论】:

标签: php html string variables input


【解决方案1】:

你可以试试

$text = str_replace("%color%", $color, $text );
$text = str_replace("%animal%", $animal, $text );

【讨论】:

  • 真的,谢谢。有什么办法可以缩短它以将变量存储在数组中?
  • @LeonardoGirardi 请参阅我回答的第二部分。
【解决方案2】:

使用phpprintf函数

 $color = 'red';
 $animal = 'cat';
 printf("The quick %s fox jumps over the lazy %s",$color,$animal);

【讨论】:

    【解决方案3】:

    如果您相信您的输入,请使用 preg_replace:

    $color = 'white';
    $animal = 'cat';
    $text = "The quick %color% fox jumps over the lazy %animal%.";
    
    $result = preg_replace('/\%([a-z]+)\%/e', "$$1", $text);
    

    这意味着从 a-z 到 % 字符之间的任何小写字符都将替换为该名称的 PHP 变量。如果您不信任自己的输入,这会带来巨大的安全风险,您应该进行某种检查以确保允许访问这些变量。

    str_replace 解决方案:

    $color = 'white';
    $animal = 'cat';
    $text = "The quick %color% fox jumps over the lazy %animal%.";
    $vars = array("color","animal");
    
    foreach ($vars as $var) {
    $text = str_replace("%{$var}%",$$var,$text);
    }
    echo $text;
    

    只是为了在双美元符号($$)表示变量变量之前没有使用过它的人进一步解释:http://php.net/manual/en/language.variables.variable.php

    【讨论】:

    • 如果您不信任输入,stackoverflow.com/a/3763835/2619379 是一个很好的解决方案 - 您可以定义一个允许/列入白名单的变量数组。
    • 谢谢,这就是我要找的!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-02
    • 2014-04-25
    • 2021-01-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多