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.
Related
I'm making an application to remove additive or commonly called Stemming confix stripping. I wanted to make a loop to process stemming in each text file. process stemming I've put them in the loop. making the process the content of each document also I put in a text file. when I run in the browser no error but only the note NULL. what's the solution? I attach my program and program results`it is code
<?php
require_once __DIR__ . '/vendor/autoload.php';
$array_sentence = glob('../../ujicoba/simpantoken/*.txt');
settype($array_sentence, "string");
if(is_array($array_sentence) && is_object($array_sentence))
{
foreach ($array_sentence as $text)
{
$textnormalizer = new src\Sastrawi\Stemmer\Filter\TextNormalizer();
$stemmerFactory = new \Sastrawi\Stemmer\StemmerFactory();
$stemmer = $stemmerFactory->createStemmer();
$content = file_get_contents($text);
$stemmer = $stemmerFactory->createStemmer();
$output = $stemmer->stem(array($content));
echo $output . "\n";
}
}
var_dump($content);
?>
<!DOCTYPE html>
<html>
<head>
<title>Confix Stripping Stemmer</title>
</head>
<body>
</body>
</html>
my source code result in browser when running programenter code here
On l.4, settype($array_sentence, "string"); force $array_sentence as a string, which means is_array($array_sentence) && is_object($array_sentence) will return false.
The following code works for stemming:
<?php
include('stopword.php');
$regexRules = array(
'/^be(.*)lah$/',
'/^be(.*)an$/',
'/^me(.*)i$/',
'/^di(.*)i$/',
'/^pe(.*)i$/',
'/^ter(.*)i$/',
'/^di(.*)kan$/',
'/^di(.*)nya$/',
'/^di(.*)kannya$/',
'/^mem(.*)pe$/',
'/^meng(.*)g$/',
'/^meng(.*)h$/',
'/^meng(.*)q$/',
'/^meng(.*)k$/',
'/^mem(.*)kan$/',
'/^diper(.*)i$/',
'/^di(.*)i$/',
'/^memper(.*)kan$/',
'/^meny(.*)i$/',
'/^meny(.*)kan$/',
'/^men(.*)kan$/',
'/^me(.*)kan$/',
'/^meng(.*)nya$/',
'/^memper(.*)i$/',
'/^men(.*)i$/',
'/^meng(.*)i$/',
'/^ber(.*)nya$/',
'/^ber(.*)an$/',
'/^ke(.*)an$/',
'/^ke(.*)annya$/',
'/^peng(.*)an$/',
'/^peny(.*)an$/',
'/^per(.*)an$/',
'/^pen(.*)an$/',
'/^pe(.*)an$/',
'/^ber(.*)$/',
'/^di(.*)$/',
'/^men(.*)$/',
'/^meng(.*)$/',
'/^meny(.*)$/',
'/^mem(.*)$/',
'/^pen(.*)$/',
'/^peng(.*)$/',
'/^ter(.*)$/',
'/^mem(.*)$/',
'/^(.*)nya$/',
'/^(.*)lah$/',
'/^(.*)pun$/',
'/^(.*)kah$/',
'/^(.*)mu$/',
'/^(.*)an$/',
'/^(.*)kan$/',
'/^(.*)i$/',
'/^(.*)ku$/',
);
global $regexRules;
$file_string = glob('yourfoldertoseavedata_text/*.txt');
$string = array('(.*)');
foreach ($file_string as $data)
{
$string[] = file_get_contents($data);
$stemming = str_ireplace($regexRules,"", $string);
var_dump($stemming);
}
?>
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;
So right now, I have a simple function that I use to call some text content:
function htmlstuff() { ?>
<p>html text content here</p>
<? }
And on a page I call the text using:
<?php htmlstuff() ?>
Now, I need to figure out how to use "search and replace" for whatever text is in the function. I've tried things like
function str_replace($search,$replace,htmlstuff())
but I obviously don't know what the heck I'm doing. Is there any simple way to just search the text within the function and search/replace?
what do you really want to do?
if you want to search and replace and in the return variable of your htmlstuff function then
you are not too far away from the correct answer.
function htmlstuff() {
$htmlstuff = "<p>html text content here</p>";
return $htmlstuff;
}
echo htmlstuff();
str_replace($search,$replace,htmlstuff());
this should do the trick
if you just want to make the function htmlstuff more dynamic, then you should take a different approach. something like this:
function htmlstuff($html) {
$htmlstuff = "<p>".$html."</p>";
return $htmlstuff;
}
echo htmlstuff("html text content here");
It would seem like this:
function htmlstuff ($content = "Default text goes here")
{
echo "<p>" . $content . "</p>";
}
and then on another call you just htmlstuff("New text to go there");
And if I'm wrong correct me to solve the problem
<?php
$html_stuff = htmlstuff();
$search_for = "Hello, world!";
$replace_with = "Goodbye, world!";
$html_stuff = str_replace($search_for, $replace_with, $html_stuff);
echo $html_stuff;
function htmlstuff() {
echo '<p>html text content here</p> ';
}
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'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