php - 检查字符串以查找内部变量(PHP)

标签 php html string variables input

我需要读取一个字符串来查找变量(标签)并将其替换为存储的值。 我使用%(百分比)来标识标签。输入应该接受一些标签,例如%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%/

最佳答案

你可以试试

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

关于php - 检查字符串以查找内部变量(PHP),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17872598/

相关文章:

java - 如何让 toString() 返回多行字符串?

php - “i360: Error in global initialization”在PHP中是什么意思?

php - 仅限管理员访问网页

jquery - HTML5数据元素避免0

c - 将字符串传递给 C 中的函数

c++ - 我需要知道如何将 c 字符串从一个变量复制到另一个变量,以便让第三个函数在我的程序中工作

php - 从数据库加载消息

php - ExpressionEngine no_results 不工作

html - 根据表格大小调整表格内图像的大小

regex - 如何使用 HTML5 验证日期模式