使用 PHP 替换纯文本变量的最佳方法

发布于 2024-07-09 17:18:06 字数 1447 浏览 7 评论 0原文

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

情感失落者 2024-07-16 17:18:07

根据具体情况, str_replace 可能会起作用。

示例:

// -- myFile.txt --
Mary had a little %pet%.

// -- parser.php --
$pet = "lamb";
$fileName = myFile.txt

$currentContents = file_get_contents($fileName);

$newContents = str_replace('%pet%', $pet, $currentContents);

// $newContents == 'Mary had a little lamb.'

当您查看 str_replace 时,请注意搜索和替换参数可以采用值数组来搜索和替换。

Depending on the situation, str_replace might do the trick.

Example:

// -- myFile.txt --
Mary had a little %pet%.

// -- parser.php --
$pet = "lamb";
$fileName = myFile.txt

$currentContents = file_get_contents($fileName);

$newContents = str_replace('%pet%', $pet, $currentContents);

// $newContents == 'Mary had a little lamb.'

When you look at str_replace note that search and replace parameters can take arrays of values to search for and replace.

惟欲睡 2024-07-16 17:18:07

您可以使用 strtr

$text = file_get_contents('/path/to/myFile.txt'); // "Mary had a little $pet."
$allVars = get_defined_vars(); // array('pet' => 'lamb');
$translate = array();

foreach ($allVars as $key => $value) {
    $translate['

您可能想在 get_define_vars() 中进行前置,所以您不需要循环变量两次。 或者更好的是,只需确保您最初分配的任何键与您在 myFile.txt 中使用的标识符匹配即可。

. $key] = $value; // prepend '

您可能想在 get_define_vars() 中进行前置,所以您不需要循环变量两次。 或者更好的是,只需确保您最初分配的任何键与您在 myFile.txt 中使用的标识符匹配即可。

to vars to match text } // translate is now array('$pet' => 'lamb'); $text = strtr($text, $translate); echo $text; // "Mary had a little lamb."

您可能想在 get_define_vars() 中进行前置,所以您不需要循环变量两次。 或者更好的是,只需确保您最初分配的任何键与您在 myFile.txt 中使用的标识符匹配即可。

You could use strtr:

$text = file_get_contents('/path/to/myFile.txt'); // "Mary had a little $pet."
$allVars = get_defined_vars(); // array('pet' => 'lamb');
$translate = array();

foreach ($allVars as $key => $value) {
    $translate['

You probably want to do the prepending in get_defined_vars(), so you don't loop the variables twice. Or better yet, just make sure whatever keys you assign initially match the identifier you use in myFile.txt.

. $key] = $value; // prepend '

You probably want to do the prepending in get_defined_vars(), so you don't loop the variables twice. Or better yet, just make sure whatever keys you assign initially match the identifier you use in myFile.txt.

to vars to match text } // translate is now array('$pet' => 'lamb'); $text = strtr($text, $translate); echo $text; // "Mary had a little lamb."

You probably want to do the prepending in get_defined_vars(), so you don't loop the variables twice. Or better yet, just make sure whatever keys you assign initially match the identifier you use in myFile.txt.

过去的过去 2024-07-16 17:18:06

正则表达式很容易。 并且它不会关心 eval() 会认为语法错误的事情。

以下是查找 PHP 样式变量名称的模式。

\$\w+

我可能会采用这种通用模式并使用 PHP 数组来查找我找到的每个匹配项(使用 (preg_replace_callback()))。这样,正则表达式只需应用一次,速度更快从长远来看。

$allVars = get_defined_vars();
$file = file_get_contents('myFile.txt');

// unsure if you have to use single or double backslashes here for PHP to understand
preg_replace_callback ('/\$(\w+)/', "find_replacements", $file);

// replace callback function
function find_replacements($match)
{
  global $allVars;
  if (array_key_exists($match[1], $allVars))
    return $allVars[$match[1]];
  else
    return $match[0];
}

Regex would be easy enough. And it would not care about things that eval() would consider a syntax error.

Here's the pattern to find PHP style variable names.

\$\w+

I would probably take this general pattern and use a PHP array to look up each match I've found (using (preg_replace_callback()). That way the regex needs to be applied only once, which is faster on the long run.

$allVars = get_defined_vars();
$file = file_get_contents('myFile.txt');

// unsure if you have to use single or double backslashes here for PHP to understand
preg_replace_callback ('/\$(\w+)/', "find_replacements", $file);

// replace callback function
function find_replacements($match)
{
  global $allVars;
  if (array_key_exists($match[1], $allVars))
    return $allVars[$match[1]];
  else
    return $match[0];
}
春花秋月 2024-07-16 17:18:06

如果它来自可信来源,您可以使用(戏剧性停顿)eval()(观众惊恐地喘息) )。

$text = 'this is a $test'; // single quotes to simulate getting it from a file
$test = 'banana';
$text = eval('return "' . addslashes($text) . '";');
echo $text; // this is a banana

If it's from a trusted source you can use (dramatic pause) eval() (gasps of horror from the audience).

$text = 'this is a $test'; // single quotes to simulate getting it from a file
$test = 'banana';
$text = eval('return "' . addslashes($text) . '";');
echo $text; // this is a banana
已下线请稍等 2024-07-16 17:18:06

这是我刚刚想到的,但我仍然有兴趣知道是否有更好的方法。 干杯。

$allVars = get_defined_vars();
$file = file_get_contents('myFile.txt');

foreach ($allVars as $var => $val) {
    $file = preg_replace("@\\$" . $var . "([^a-zA-Z_0-9\x7f-\xff]|$)@", $val . "\\1", $file);
}

Here's what I've just come up with, but I'd still be interested to know if there's a better way. Cheers.

$allVars = get_defined_vars();
$file = file_get_contents('myFile.txt');

foreach ($allVars as $var => $val) {
    $file = preg_replace("@\\$" . $var . "([^a-zA-Z_0-9\x7f-\xff]|$)@", $val . "\\1", $file);
}
时常饿 2024-07-16 17:18:06

一定是$pet吗? 可以改为 吗? 因为如果是这样,只需使用 include 即可。 这就是 php 作为模板引擎的整体思想。

//myFile.txt
Mary had a little <?= $pet ?>.

//parser.php

$pet = "lamb";
ob_start();
include("myFile.txt");
$contents = ob_end_clean();

echo $contents;

这将回显:

Mary had a little lamb.

Does it have to be $pet? Could it be <?= $pet ?> instead? Because if so, just use include. This is the whole idea of php as a templating engine.

//myFile.txt
Mary had a little <?= $pet ?>.

//parser.php

$pet = "lamb";
ob_start();
include("myFile.txt");
$contents = ob_end_clean();

echo $contents;

This will echo out :

Mary had a little lamb.
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文