suppose i have a variable in a seperate php file i.e
$imgfile = "images/img.jpg";
now i have a php file where i am including a html or another php file i.e
<?php
include("foo.html");
?>
and in foo.html i have the following code..
<html>
<head>
<title>foo site</title>
</head>
<body>
<img src="<?php echo $imgfile; ?>">
and it is works but i am including that $imgfile many times so i want not to type
<?php echo $imgfile; ?> again and again.. i have seen many scripts that include such files by just typing {$imgfile} but i don't know how to use it please let me know how can i use such a format..??
PHP is a template engine already.
so, it has shorter form for echo statement, especially for this purpose:
<?=$imgfile?>
considerable shorter and comparable to {$imgfile}
Note that to make use of brackets, you'll have to devise alternatives for loops, conditions and other statements, which will complicate your life.
while using PHP as a template, you'll be able to use built-in PHP operators, like foreach or if or include.
So, it would be better to stick to <?=$imgfile?> syntax.
Just make sure you have short_open_tags setting turned on
I think Smarty, a templating engine, is what you are looking for. See this link: http://smarty.net/
In order to achieve this behavior you should use a template engine like Smarty or write your own interpreter that will replace such expressions with the appropriate values.
e.g.
$buffer = 'Hello {$world}';
$world = "World";
if(preg_match_all("/{([^}]+)}/im", $buffer, $matches, PREG_SET_ORDER)) {
foreach($matches as $match) {
$expression = $match[0];
$exactMatch = $match[1];
if(defined($exactMatch)) {
$buffer = str_replace($expression, constant($exactMatch), $buffer);
} else {
if(strrpos($exactMatch, "$") !== false) {
$vars = get_defined_vars();
$var = str_replace("$", "", $exactMatch);
if(isset($vars[$var])) {
$buffer = str_replace($expression, $vars[$var], $buffer);
}
}
if(is_callable($exactMatch)) {
$buffer = str_replace($expression, call_user_func($exactMatch), $buffer);
}
}
}
}
echo $buffer;
There are three options for you here.
1) assign <img src="<?php echo $imgfile; ?>"> to a shorter string
$a = "<img src='$imgfile'>";
Then in your templates
<html>
<head>
<title>foo site</title>
</head>
<body>
<img src="<?php echo $imgfile; ?>">
2) Use a placeholder then buffer and post process your output.
In your templates
<?php echo ob_start('myReplacementCallback') ?>
<html>
<head>
<title>foo site</title>
</head>
<body>
{{imgfile}}
<?php ob_end_flush (); ?>
Define myReplacementCallback somewhere:
function myReplacementCallback($contents) {
$replacements = array(
'{{imgfile}}' => "<img src='/path/to/image'>",
);
return str_replace(array_keys($replacements), $replacements, $contents);
}
3) Use a template engine like twig or smarty. (Prefered method)
Related
I am using simple-html-dom for my work. I want to get all PHP script (<?php ... ?>) form file using simple-html-dom.
if i have one file (name: text.php) with below code :
<html>
<head>
<title>Title</title>
</head>
<body>
<?php echo "This is test Text"; ?>
</body>
</html>
then how can i get this PHP script <?php echo "This is test Text"; ?> form above file of code using simple-html-dom.
$html = file_get_html('text.php');
foreach($html->find('<?php') as $element) {
//Sonthing code ...
}
i can not use like this, Is there any other option for this ?
Here's a solution using regex. Note that regex often is not advisable for parsing HTML files. That is, it might be okay in this case.
This will match each instance of a PHP code block and allow you to output (or do whatever else you want) either the entire block (including the tags) or the code that is contained within the block. See the documentation for preg_match_all().
<?php
$string = <<<'NOW'
<html>
<head>
<title>Title</title>
<?php echo "something else"; ?>
</head>
<body>
<?php echo "This is test Text"; ?>
</body>
</html>
NOW;
preg_match_all("/\<\?php (.*) \?\>/", $string, $matches);
foreach($matches[0] as $index => $phpBlock)
{
echo "Full block: " . $phpBlock;
echo "\n\n";
echo "Command: " . $matches[1][$index];
echo "\n\n";
}
DEMO
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;
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.
I am trying to remove script tags from HTML using PHP but it doesn't work if there's HTML inside the javascript.
For example, if the script tags contain something like this:
function tip(content) {
$('<div id="tip">' + content + '</div>').css
It will stop at </div> and the rest of the script will still be taken into account.
This is what I have been using to remove the script tags:
foreach ($doc->getElementsByTagName('script') as $node)
{
$node->parentNode->removeChild($node);
}
How about some regex-based pre-processing?
Example input.html:
<html>
<head>
<title>My example</title>
</head>
<body>
<h1>Test</h1>
<div id="foo"> </div>
<script type="text/javascript">
document.getElementById('foo').innerHTML = '<span style="color:red;">Hello World!</span>';
</script>
</body>
</html>
Script tag removing php script:
<?php
// unformatted source output:
header("Content-Type: text/plain");
// read the example input file given above into a string:
$input = file_get_contents('input.html');
echo "Before:\r\n";
echo $input;
echo "\r\n\r\n-----------------------\r\n\r\n";
// replace script tags including their contents by ""
$output = preg_replace("~<script[^<>]*>.*</script>~Uis", "", $input);
echo "After:\r\n";
echo $output;
echo "\r\n\r\n-----------------------\r\n\r\n";
?>
You can use strip_tags function. In which you can allow the HTML attributes which you want allowed.
I think this is 'here and now' problem, and you need no something special. Just do something like this:
$text = file_get_content('index.html');
while(mb_strpos($text, '<script') != false) {
$startPosition = mb_strpos($text, '<script');
$endPosition = mb_strpos($text, '</script>');
$text = mb_substr($text, 0, $startPosition).mb_substr($text, $endPosition + 7, mb_strlen($text));
}
echo $text;
Only set encoding for 'mb_' like functions
I am requesting the source code of a website like this:
<? $txt = file_get_contents('http://stats.pingdom.com/qmwwuwoz2b71/522741');
echo $txt; ?>
Bu I would like to replace the relative links with absolute ones! Basically,
<img src="/images/legend_15s.png"/> and <img src='/images/legend_15s.png'/>
should be replaced by
<img src="http://domain.com/images/legend_15s.png"/>
and
<img src='http://domain.com/images/legend_15s.png'/>
respectively. How can I do this?
This can be acheived with the following:
<?php
$input = file_get_contents('http://stats.pingdom.com/qmwwuwoz2b71/522741');
$domain = 'http://stats.pingdom.com/';
$rep['/href="(?!https?:\/\/)(?!data:)(?!#)/'] = 'href="'.$domain;
$rep['/src="(?!https?:\/\/)(?!data:)(?!#)/'] = 'src="'.$domain;
$rep['/#import[\n+\s+]"\//'] = '#import "'.$domain;
$rep['/#import[\n+\s+]"\./'] = '#import "'.$domain;
$output = preg_replace(
array_keys($rep),
array_values($rep),
$input
);
echo $output;
?>
Which will output links as follows:
/something
will become,
http://stats.pingdom.com//something
And
../something
will become,
http://stats.pingdom.com/../something
But it will not edit "data:image/png;" or anchor tags.
I'm pretty sure the regular expressions can be improved though.
This code replaces only the links and images:
<? $txt = file_get_contents('http://stats.pingdom.com/qmwwuwoz2b71/522741');
$txt = str_replace(array('href="', 'src="'), array('href="http://stats.pingdom.com/', 'src="http://stats.pingdom.com/'), $txt);
echo $txt; ?>
I have tested and its working :)
UPDATED
Here is done with regular expression and working better:
<? $txt = file_get_contents('http://stats.pingdom.com/qmwwuwoz2b71/522741');
$domain = "http://stats.pingdom.com";
$txt = preg_replace("/(href|src)\=\"([^(http)])(\/)?/", "$1=\"$domain$2", $txt);
echo $txt; ?>
Done :D
You dont need php, you only need to use the html5 base tag, and put your php code in html body, you only need to do the following
Example :
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<base href="http://yourdomain.com/">
</head>
<body>
<? $txt = file_get_contents('http://stats.pingdom.com/qmwwuwoz2b71/522741');
echo $txt; ?>
</body>
</html>
and all the files will use the absolute url