首页 > 解决方案 > 允许用户在 PHP 中使用一些静态值创建自定义段落

问题描述

让我们说这是静态字符串:

$name = "John";
$age = 37;

现在,假设用户在 Textarea 中输入以下值:

His name is {name}. His age is {age}

他还可以键入:

{name} is his name. {age} is his age.

现在,当用户提交表单时,PHP 应该将这些字符串设置到那些特定位置。

例如输出应该是这样的:

His name is John. His age is 37

John is his name. 37 is his age.

标签: php

解决方案


好的,由于您没有提供问题的具体细节,我只能推测您可能想要这个:

<?php

$name = "John";
$age = 37;

$userInput1 = "His name is {name}. His age is {age}";
$userInput2 = "{name} is his name. {age} is his age.";

$result1 = str_replace("{name}", $name, $userInput1);
$result1 = str_replace("{age}", $age, $result1);

$result2 = str_replace("{name}", $name, $userInput2);
$result2 = str_replace("{age}", $age, $result2);

echo "$result1<br>$result2";

这只是一个非常简单的文本替换。

按照你说的,让用户从textarea输入,然后传给php,输出结果。这是一个演示:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <form action="a.php" method="post">
        <textarea name="text_from_textarea"></textarea>
        <button type="submit">Submit</button>
    </form>
</body>
</html>
<?php

$name = "John";
$age = 37;

$userInput = $_POST["text_from_textarea"];

$result = str_replace("{name}", $name, $userInput);
$result = str_replace("{age}", $age, $result);

echo "$result";

推荐阅读