PHP include HTML and echo out variable - php

I am working on a script with templates. So I have this PHP code:
<?php
$string = "TEST";
echo(file_get_contents('themes/default/test.html'));
?>
And I have this HTML (the test.html file):
<html>
<p>{$string}</p>
</html>
How can I make PHP actually display the variable inside the curly brackets? At the moment it displays {$string}.
P.S:
The string might also be an object with many many variables, and I will display them like that: {$object->variable}.
P.S 2: The HTML must stay as it is. This works:
$string = "I'm working!"
echo("The string is {$string}");
I need to use the same principle to display the value.

You can use the following code to achieve the desired result:
<?php
$string = "TEST";
$doc = file_get_contents('themes/default/test.html'));
echo preg_replace('/\{([A-Z]+)\}/', "$$1", $doc);
?>
P.S. Please note that it will assume that every string wrapped in { }
has a variable defined. So No error checking is implemented in the code above. furthermore it assumes that all variables have only alpha characters.

If it is possible to save your replacees in an array instead of normal variables you could use code below. I'm using it with a similar use case.
function loadFile($path) {
$vars = array();
$vars['string'] = "value";
$patterns = array_map("maskPattern", array_keys($vars));
$result = str_replace($patterns, $vars, file_get_contents($path));
return $result;
}
function maskPattern($value) {
return "{$" . $value . "}";
}

All you PHP must be in a <?php ?> block like this:
<html>
<p><?php echo "{" . $string . "}";?></p>
</html>

If you know the variable to replace in the html you can use the PHP function 'str_replace'. For your script,
$string = "TEST";
$content = file_get_contents('test.html');
$content = str_replace('{$string}', $string, $content);
echo($content);

It's simple to use echo.
<html>
<p>{<?php echo $string;?>}</p>
</html>
UPDATE 1:
After reading so many comments, found a solution, try this:
$string = "TEST";
$template = file_get_contents('themes/default/test.html', FILE_USE_INCLUDE_PATH);
$page = str_replace('{$string}',$string,$template);
echo $page;

Related

PHP - How remove blank line where placeholder used to be?

I came across this old post while searching for a way to efficiently replace placeholders in a template file.
Everything seems to be working however, there are some values which are optional and the best I've been able to do is replace the placeholders with empty strings, which still leaves blank lines.
The current code I'm testing with is below:
test.php:
<?php
$text = file_get_contents('test.html');
$pattern = '/{{{([a-zA-Z0-9_]+)}}}/';
$text = preg_replace_callback($pattern, 'produce_replacement', $text);
echo $text;
function produce_replacement($match) {
$producerName = 'evaluate_'.strtolower($match[1]);
return function_exists($producerName) ? $producerName() : null;
}
function evaluate_test1() {
ob_start();
include'test_include.php';
$test4 = ob_get_clean();
return $test4;
}
function evaluate_footer() {
if (isset($blah)) {
$val = 'some string';
} else {
$val = '';
}
return $val;
}
?>
test.html (template file):
<html>
<head></head>
<body>
<p>Test1: {{{test1}}}</p>
<p>Test2: {{{test2}}}</p>
<p>Test3: {{{test3}}}</p>
<p>Test4: {{{test4}}}</p>
{{{footer}}}
</body>
</html>
test_include.php:
<?php
$a = 'Hi, ';
$b = 'jeff!';
echo $a.$b;
?>
So {{{footer}}} will be replaced with $val which will be either some string or a blank line will remain. How can I get rid of that blank line?
Your code is working as expected. The newline character exists in your template file, you need to update it:
<html>
<head></head>
<body>
<p>Test1: {{{test1}}}</p>
<p>Test2: {{{test2}}}</p>
<p>Test3: {{{test3}}}</p>
<p>Test4: {{{test4}}}</p>
{{{footer}}}</body>
</html>
However I don't see the problem with that whitespace, a browser would not render it anyway.

How can I replace braces with <?php ?> in php file?

I wanna replace braces with <?php ?> in a file with php extension.
I have a class as a library and in this class I have three function like these:
function replace_left_delimeter($buffer)
{
return($this->replace_right_delimeter(str_replace("{", "<?php echo $", $buffer)));
}
function replace_right_delimeter($buffer)
{
return(str_replace("}", "; ?> ", $buffer));
}
function parser($view,$data)
{
ob_start(array($this,"replace_left_delimeter"));
include APP_DIR.DS.'view'.DS.$view.'.php';
ob_end_flush();
}
and I have a view file with php extension like this:
{tmp} tmpstr
in output I save just tmpstr and in source code in browser I get
<?php echo $tmp; ?>
tmpstr
In include file <? shown as <!--? and be comment. Why?
What you're trying to do here won't work. The replacements carried out by the output buffering callback occur after PHP code has already been parsed and executed. Introducing new PHP code tags at this stage won't cause them to be executed.
You will need to instead preprocess the PHP source file before evaluating it, e.g.
$tp = file_get_contents(APP_DIR.DS.'view'.DS.$view.'.php');
$tp = str_replace("{", "<?php echo \$", $tp);
$tp = str_replace("}", "; ?>", $tp);
eval($tp);
However, I'd strongly recommend using an existing template engine; this approach will be inefficient and limited. You might want to give Twig a shot, for instance.
do this:
function parser($view,$data)
{
$data=array("data"=>$data);
$template=file_get_contents(APP_DIR.DS.'view'.DS.$view.'.php');
$replace = array();
foreach ($data as $key => $value) {
#if $data is array...
$replace = array_merge(
$replace,array("{".$key."}"=>$value)
);
}
$template=strtr($template,$replace);
echo $template;
}
and ignore other two functions.
How does this work:
process.php:
<?php
$contents = file_get_contents('php://stdin');
$contents = preg_replace('/\{([a-zA-Z_][a-zA-Z_0-9]*)\}/', '<?php echo $\1; ?>', $contents);
echo $contents;
bash script:
process.php < my_file.php
Note that the above works by doing a one-off search and replace. You can easily modify the script if you want to do this on the fly.
Note also, that modifying PHP code from within PHP code is a bad idea. Self-modifying code can lead to hard-to-find bugs, and is often associated with malicious software. If you explain what you are trying to achieve - your purpose - you might get a better response.

Error using preg_relace to change url youtube?

I have a sample code:
<?php
$url = 'http://www.youtube.com/watch?v=KTRPVo0d90w';
$pattern = '/http:\/\/www\.youtube\.com\/watch\?(.*?)v=([a-zA-Z0-9_\-]+)(\S*)/i';
$replace = $pattern.'&w=550';
$string = preg_replace($pattern, $replace, $url);
?>
How to result is http://www.youtube.com/watch?v=KTRPVo0d90w&w=550
You can just append using the . operator:
<?php
$url = 'http://www.youtube.com/watch?v=KTRPVo0d90w';
$string = $url.'&w=550';
?>
Use preg_match instead:
<?php
$url = 'http://www.youtube.com/watch?v=KTRPVo0d90w&s=222';
$pattern = '/v=[^&]+/i';
preg_match($pattern, $url, $match);
echo 'http://www.youtube.com/watch?'.$match[0].'&w=550';
?>
Like below?
$url = 'http://www.youtube.com/watch?v=KTRPVo0d90w';
$bit = '&w=550';
echo "${url}${bit}";
Don't get me wrong, I'm not looking to gain any points here, but just thought I would add to this question and include a few options. I love toying with ideas like this every once in a while.
Using jh314's idea to concatenate the strings, thought that this could be used for future use, to actually replace a string inside the video's YouTube number, should the occasion ever present itself.
Such as $number for instance.
<?php
$url = 'http://www.youtube.com/watch?v=';
$number = 'KTRPVo0d90w';
$string = $url.$number.'&w=550';
// Output to screen
echo $string;
echo "<br>";
// Link to video
echo "Click for the video";
?>
The same could easily be done for the video's width.

Get code between php tags with regular expression

I'm trying to get php code out of a HTML template file to execute it and place the result back.
What regular expression code can I use? And is there a method that also return the position of the found first tag?
<p>some html</p>
<?php $some = "php code"; ?>
<p>some <em>more</em> html</p>
<?php $some = "more php code"; ?>
I want the php code filtered from the html.
preg_match("/<\?.*?\?>/m",$output,$matches)
or
preg_match("/<\?.*?\?>/s",$output,$matches)
Should match all lines.
Instead of "getting the PHP out and putting it back" you should pass the variables to the template file.
Something like this:
<?php
function loadTemplate($path,$data=array()){
if (file_exists($path) === false){
throw new Exception('Template not found:'.$path);
return false;
}
extract($data);
ob_start();
require($path);
$return = ob_get_contents();
ob_end_clean();
return $return;
}
$vars = array('var1'=>$value,
'var2'=>$somevalue,
'var3'=>$someothervalue,
'var4'=>$blab);
$template = loadTemplate('path/to/thefile.php',$vars);
?>
Then access the $vars array values from within thefile.php like
echo $var1
echo $var2
ect
Hope it helps

Why won't this work in PHP?

$constPrefix = '_CONST_';
if (strstr($content, $constPrefix)) {
$constants = array('PHP_VERSION', '__FILE__');
foreach($constants as $constant) {
$constantOutput = eval($constant);
$content = str_replace($constPrefix . $constant, $constantOutput, $content);
}
}
Basically, just trying to parse some content and replace strings inside with the equivalent PHP constant. Is eval() what I should be using here? I've never actually found a reason to use it before, and it's almost 1am, and am wondering if that is a coincidence?
You can replace eval with constant:
$constantOutput = constant($constant);
Why don't you just leave out the eval?
<?php
$v = PHP_VERSION;
$f = __FILE__;
echo $v.' '.$f;
?>
gives
/tmp% php test.php
5.2.10-2ubuntu6.4 /tmp/test.php

Categories