I have searched this problem for a while now, maybe it is simple or maybe not. I could not figure out how to get this to work.
My goal outcome would be a hyperlink related to the post meta with some styling like so.
Check out the r_title here!
The code I have is:
<?php
$rtitle1 = get_post_meta($post->ID, 'r_title', true);
$rlink1 = get_post_meta($post->ID, 'href_link', true);
function testfunction() {
$output .= '<a href=\"'$rlink1'\" style=\"color: #e67300\" rel=\"nofollow\">';
$output .= ' Check out the '$rtitle1' here!</a>';
return $output;
}
add_shortcode('shortcode', 'testfunction');
?>
There are several problems with your code.
The first problem is with string concatenation. When you want to glue strings together you need to use the concatenation operator (the dot: .):
$end = 'a string';
$start = 'This is ';
$string = $start.$end;
If you just juxtapose variables and strings (or any other scalar types) then you will get errors:
$end = 'a string';
$string = "This is "$end; // Error!
The second problem is that you are using two variables ($rtitle1 and $rlink1) that are in the global scope. If you want to use global variables inside a function then you need to declare them as global inside the function:
$globalVar = 'test';
function test() {
global $globalVar;
echo $globalVar;
}
The third problem is that you forgot the ending closing parenthesis, ), for the get_post_meta() function:
$rtitle1 = get_post_meta($post->ID, 'r_title', true;
$rlink1 = get_post_meta($post->ID, 'href_link', true;
They should be like this:
$rtitle1 = get_post_meta($post->ID, 'r_title', true);
$rlink1 = get_post_meta($post->ID, 'href_link', true);
Before you think about asking for help you should look at the error messages that you get. If you have not seen the error message before then Google it. The best way to learn something is to find the solution on your own. Asking questions is for when you have tried finding a solution but you cannot find it.
Related
I'm need to concatenate lines for later output (markdown processing...). This is why I use a function l() and a global variable $content.
My view code:
$content = "";
function l($line="") {
global $content;
$content .= $line."\n";
}
l("hello");
echo "+";
echo $content;
echo "-";
outputs
+-
I'd expect:
+Hello-
Why? What am I doing wrong?
I am using PHP 7.2.6
EDIT:
There are several PHP related answers as this one. But they don't help. I suppose the problem is related to Yii2 and more specific to Yii2 view handling.
Found the solution! Crazy!
Yii2 renders the view inside an object instance.
This means, the PHP variable declaration
$content = "";
is not global but local to the rendering context.
The solution for question is to make the variable declaration in the view global, too:
global $content = "";
The working code inside the view looks like this now:
global $content = "";
function l($line="") {
global $content;
$content .= $line."\n";
}
l("hello");
echo "+";
echo $content;
echo "-";
Bingo!
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 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.
I'm including a file in one of my class methods, and in that file has html + php code. I return a string in that code. I explicitly wrote {{newsletter}} and then in my method I did the following:
$contactStr = include 'templates/contact.php';
$contactStr = str_replace("{{newsletter}}",$newsletterStr,$contactStr);
However, it's not replacing the string. The only reason I'm doing this is because when I try to pass the variable to the included file it doesn't seem to recognize it.
$newsletterStr = 'some value';
$contactStr = include 'templates/contact.php';
So, how do I implement the string replacement method?
You can use PHP as template engine. No need for {{newsletter}} constructs.
Say you output a variable $newsletter in your template file.
// templates/contact.php
<?= htmlspecialchars($newsletter, ENT_QUOTES); ?>
To replace the variables do the following:
$newsletter = 'Your content to replace';
ob_start();
include('templates/contact.php');
$contactStr = ob_get_clean();
echo $contactStr;
// $newsletter should be replaces by `Your content to replace`
In this way you can build your own template engine.
class Template
{
protected $_file;
protected $_data = array();
public function __construct($file = null)
{
$this->_file = $file;
}
public function set($key, $value)
{
$this->_data[$key] = $value;
return $this;
}
public function render()
{
extract($this->_data);
ob_start();
include($this->_file);
return ob_get_clean();
}
}
// use it
$template = new Template('templates/contact.php');
$template->set('newsletter', 'Your content to replace');
echo $template->render();
The best thing about it: You can use conditional statements and loops (full PHP) in your template right away.
Use this for better readability: https://www.php.net/manual/en/control-structures.alternative-syntax.php
This is a code i'm using for templating, should do the trick
if (preg_match_all("/{{(.*?)}}/", $template, $m)) {
foreach ($m[1] as $i => $varname) {
$template = str_replace($m[0][$i], sprintf('%s', $varname), $template);
}
}
maybe a bit late, but I was looking something like this.
The problem is that include does not return the file content, and easier solution could be to use file_get_contents function.
$template = file_get_contents('test.html', FILE_USE_INCLUDE_PATH);
$page = str_replace("{{nombre}}","Alvaro",$template);
echo $page;
based on #da-hype
<?php
$template = "hello {{name}} world! {{abc}}\n";
$data = ['name' => 'php', 'abc' => 'asodhausdhasudh'];
if (preg_match_all("/{{(.*?)}}/", $template, $m)) {
foreach ($m[1] as $i => $varname) {
$template = str_replace($m[0][$i], sprintf('%s', $data[$varname]), $template);
}
}
echo $template;
?>
Use output_buffers together with PHP-variables. It's far more secure, compatible and reusable.
function template($file, $vars=array()) {
if(file_exists($file)){
// Make variables from the array easily accessible in the view
extract($vars);
// Start collecting output in a buffer
ob_start();
require($file);
// Get the contents of the buffer
$applied_template = ob_get_contents();
// Flush the buffer
ob_end_clean();
return $applied_template;
}
}
$final_newsletter = template('letter.php', array('newsletter'=>'The letter...'));
<?php
//First, define in the template/body the same field names coming from your data source:
$body = "{{greeting}}, {{name}}! Are You {{age}} years old?";
//So fetch the data at the source (here we will create some data to simulate a data source)
$data_source['name'] = 'Philip';
$data_source['age'] = 35;
$data_source['greeting'] = 'hello';
//Replace with field name
foreach ($data_source as $field => $value) {
//$body = str_replace("{{" . $field . "}}", $value, $body);
$body = str_replace("{{{$field}}}", $value, $body);
}
echo $body; //hello, Philip! Are You 35 years old?
Note - An alternative way to do the substitution is to use the commented syntax.
But why does using the three square brackets work?
By default the square brackets allow you to insert a variable inside a string.
As in:
$name = 'James';
echo "His name is {$name}";
So when you use three square brackets around your variable, the innermost square bracket is dedicated to the interpolation of the variables, to display their values:
This {{{$field}}} turns into this {{field}}
Finally the replacement with str_replace function works for two square brackets.
no, don't include for this. include is executing php code. and it's return value is the value the included file returns - or if there is no return: 1.
What you want is file_get_contents():
// Here it is safe to use eval(), but it IS NOT a good practice.
$contactStr = file_get_contents('templates/contact.php');
eval(str_replace("{{newsletter}}", $newsletterStr, $contactStr));