我有一个函数:
myfunc () {
$a = "John";
$str = "Hello $a, how are you today?"
return $str;
}
echo myfunc(); //Hello John, how are you today?
我想把那个函数中的所有句子都保存到另一个文件中,因为它们的长度太长,无法放入我的函数中。
myfunc () {
$a = "John";
$str = file_get_contents("inc_file.html");
return $str;
}
inc_file.html:
Hello $a, how are you today?
但是它没有像我期望的那样返回。变量$a没有更改为John。请帮帮我!由于
file_get_contents()
所做的就是返回文件的内容,正如函数名所暗示的那样。它不像在"
s中解析字符串那样解析内容。
在返回的文件内容上使用str_replace()
似乎可以实现您想要的。
$str = file_get_contents("inc_file.html");
$str = str_replace('$a', 'John', $str);
return $str;
如果您想替换多个"变量",您可以将数组传递给str_replace
,例如
$search = [$a, $b];
$replace = ['John', 'Brian'];
$str = file_get_contents("inc_file.html");
$str = str_replace($search, $replace, $str);
return $str;
见http://php.net/manual/en/function.str-replace.php
$str = file_get_contents("inc_file.html");
行仅获取文件内容。它不计算的内容,不用的值替换的变量。
假设,如果文件很大,会有一些关于php变量的特定文本,会发生什么?
它们都应该被替换成一些值?我想没有。所以,你只有一个带有符号$a
的字符串。
如果你必须替换字符串中的东西-使用str_replace
,简单的代码是:
function myfunc () {
$a = "John";
$str = file_get_contents("inc_file.html");
return str_replace('$a', $a, $str);
}
你有什么是好的,你可以只是使用preg_replace_callback()
或在这种情况下str_replace()
做你想要的。只要做一些调整:
"Hello ~val~, how are you today?"
PHP function myfunc ($a)
{
$str = str_replace('~val~',$a,file_get_contents("inc_file.html"));
return $str;
}
echo myfunc('John');
简单preg_replace_callback()
示例:
function myfunc ($string,$a)
{
$str = preg_replace_callback('/(~[^~]{1,}~)/',function($v) use (&$a)
{
return array_shift($a);
},$string);
return $str;
}
$string = "hello my name is ~name~. I come from ~city~";
echo myfunc($string,array('John','San Francisco'));
你可以包含。php文件,但与。html不工作,因为你包含html而不是php代码。如果你像这样编写代码和文件:
<?php
function myfunc()
{
$a = "John";
$str = file_get_contents("inc_file.php");
return $str;
}
?>
inc_file.php:
Hello <?php echo $a; ?>, how are you today?
这里有一个方法可以替换加载文件字符串中的任何匹配变量。这是下面链接的代码的修改版本。我修改了它来检查字符串类型。它假设变量是全局的。
如何在没有eval的情况下输出这个动态数据?
function interpolate( $string ){
foreach ($GLOBALS as $name => $value){
// avoid array to string and object conversion errors
if(is_string($value)){
$string = str_replace( '$'.$name, $value, $string );
}
}
$string = preg_replace( '/[$]''w+/', '', $string );
return $string;
}
$emailTemplate = file_get_contents('inc_file.html');
$emailTemplate = interpolate($emailTemplate);
echo $emailTemplate;
我在寻找一种不需要eval()的方法后发现了这个问题,如下所示:
$emailTemplate = file_get_contents('inc_file.html');
$emailTemplate = htmlentities($emailTemplate);
eval("'$emailTemplate = '"$emailTemplate'";");
echo html_entity_decode($emailTemplate) ;