i was wondering if you can have conditional statments inside a heredocs, this is my script but it deosnt parse out the $username properly?
php code:
function doSomething($username) {
if (isset($_SESSION['u_name'])){
$reply ='<a class ="reply" href="viewtopic.php?replyto=#$username.&status_id=$id&reply_name=$username"> reply </a>';
return <<<ENDOFRETURN
$reply
ENDOFRETURN;
the problem with this is the $username variable deosnt get rendered on the html. it remains $username :)) thanks
Easy. Wrap everything in curly braces (obviously supported in Heredocs) and then use an anonymous function and return what is necessary for the logic :] you can even get advance with it and use expressions inside the the anonymous function variable within the heredocs.
Example:
// - ############# If statement + function to set #################
$result = function ($arg1 = false, $arg2 = false)
{
return 'function works';
};
$if = function ($condition, $true, $false) { return $condition ? $true : $false; };
// - ############# Setting Variables (also using heredoc) #########
$set = <<<HTML
bal blah dasdas<br/>
sdadssa
HTML;
$empty = <<<HTML
data is empty
HTML;
$var = 'setting the variable';
// - ############## The Heredoc ###################################
echo <<<HTML
<div style="padding-left: 34px; padding-bottom: 18px;font-size: 52px; color: #B0C218;">
{$if(isset($var), $set, $empty)}
<br/><br/>
{$result()}
</div>
HTML;
Do you want to have conditional statements in heredoc or do you wonder why your code does not work? Because currently you have no conditional statement inside heredoc, but it is not possible anyway.
If you wonder why your code does not work:
This is not related to heredoc, it is because the entire $reply string is enclosed in single quotes, where variable parsing is not supported. Use string concatenation:
$reply ='<a class ="reply" href="viewtopic.php?replyto=#' . $username . '.&status_id=$id&reply_name=' . $username . '"> reply </a>'
I hope you are doing more with heredoc in your real code, otherwise return $reply would be easier ;) (and you are missing brackets).
This question has aged a bit but to provide a more complete answer with a few possible solutions. Conditionals are not allowed "inside" a heredoc but you can use conditionals with heredocs.
These examples should give you an idea of heredoc usage. Take note that the first line of a heredoc starts with 3 less than symbols and some arbitrary text with no space at the end of the first line. Press enter. The heredoc must be closed similarly. As you probably know, the text used to open the heredoc must be used to close it which is typically but not required to be followed by a semicolon. Be sure no trailing whitespace or characters follow the semicolon or last text character and then press enter.
function doSomething($username = '', $status_id = '') {
if ('' != $username && '' != $status_id) {
$reply = <<<EOT
<a class ="reply" href="viewtopic.php?replyto=#{$username}&status_id={$status_id}&reply_name={$username}"> reply </a>
EOT;
} else {
$reply = <<<EOT
<h2>The username was not set!</h2>
EOT;
}
return $reply;
}
echo doSomething('Bob Tester', 12);
echo doSomething('Bob Tester');
echo doSomething('', 12);
Depending on your specific situation you may find it helpful to use a class to do your comparisons that you wanted to use in your heredoc. Here is an example of how you may do that.
class Test {
function Compare($a = '', $b = '') {
if ($a == $b)
return $a;
else
return 'Guest';
}
};
function doSomething($username = '') {
$Test = new Test;
$unme = 'Bob Tester';
$reply = <<<EOT
<h2>Example usage:</h2>
Welcome {$Test->Compare($username, '')}<br />
<br />
Or<br />
<br />
Welcome {$Test->Compare($username, $unme)}
EOT;
return $reply;
}
echo doSomething('Bob Tester');
Related
I'm quite new to PHP, so this is probably a stupid question.
I have an if/else that I need to use in a return tag, but it doesn't work. How should I structure this?
This is the tag:
return '… <div class="read"><a class="read-more hvr-icon-forward" href="'. get_permalink($post->ID) . '">' . "CODE HERE" . '</a></div>';
This is what I need to output in "CODE HERE"
$status = of_get_option('read_more');
if (empty($status)) {
echo 'Sorry, the page does not exist.';
} else {
_e($status);
}
https://jsfiddle.net/33nv1xpa/1/
Do I get it right, you have a structure like
return *SOME_STRING* SOME CODE WITH ";" *SOME_STRING*
?
I would highly recommend, to create a string var containing the text you want to return and finally only return that string.
$echoCode = result from CODE HERE
$returnText = "<div>blalba</div>" . $echoCode . "<div>blabla</div>";
return $returnText;
You can do it by using the ternary operator, and putting the variable assignment in parenthenses.
return "...". (($status = get_option('status')) ? $status : _e()) ."...";
Otherways, I suggest to put this functionality in a function, or at least in a plain variable.
Coding like this makes the whole thing unreadable.
Also, you're trying to run a wordpess function in an online parser which will undeniably miss these features!
Well you can use the Php eval function (http://php.net/manual/en/function.eval.php). It evaluates a string as Php code. So you can assign the result of eval to a variable called $code_here:
$code_here = "$status = of_get_option('read_more');
if (empty($status)) {
echo 'Sorry, the page does not exist.';
} else {
_e($status);
}";
$code_here = eval($code_here);
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 have a PHP function that is calling the following:
function availability_filter_func($availability) {
$replacement = 'Out of Stock - Contact Us';
if(is_single(array(3186,3518)))
$availability['availability'] = str_ireplace('Out of stock', $replacement, $availability['availability']);
}
As you can see I am replacing the text string with custom text, however
I need the "Contact Us" text to be Contact Us - how would I go about doing this? Inputting raw html into the replacement string makes the html a part of the output.
Echo does not work and breaks the PHP function - same with trying to escape the PHP function, inserting html on on the entire string, and unescape the function.
Any advice would be appreciated, thank you.
Your code seems to be a complex way of doing this
function availability_filter_func($availability) {
$default = "Out of Stock";
$string = "<a href='mailto:contact#example.com'>Contact Us</a>";
if($availablity !== "") {
$return = $availability;
} else {
$return = $default;
}
return "$return - $string";
}
Try the Heredoc Syntax
$replacement = <<<LINK
Contact Us
LINK;
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));
$var = "Hi there"."<br/>"."Welcome to my website"."<br/>;"
echo $var;
Is there an elegant way to handle line-breaks in PHP? I'm not sure about other languages, but C++ has eol so something thats more readable and elegant to use?
Thanks
For linebreaks, PHP as "\n" (see double quote strings) and PHP_EOL.
Here, you are using <br />, which is not a PHP line-break : it's an HTML linebreak.
Here, you can simplify what you posted (with HTML linebreaks) : no need for the strings concatenations : you can put everything in just one string, like this :
$var = "Hi there<br/>Welcome to my website<br/>";
Or, using PHP linebreaks :
$var = "Hi there\nWelcome to my website\n";
Note : you might also want to take a look at the nl2br() function, which inserts <br> before \n.
I have defined this:
if (PHP_SAPI === 'cli')
{
define( "LNBR", PHP_EOL);
}
else
{
define( "LNBR", "<BR/>");
}
After this use LNBR wherever I want to use \n.
in php line breaks we can use PHP_EOL (END of LINE) .it working as "\n"
but it cannot be shown on the ht ml page .because we have to give HTML break to break the Line..
so you can use it using define
define ("EOL","<br>");
then you can call it
I ended up writing a function that has worked for me well so far:
// pretty print data
function out($data, $label = NULL) {
$CLI = (php_sapi_name() === 'cli') ? 'cli' : '';
$gettype = gettype($data);
if (isset($label)) {
if ($CLI) { $label = $label . ': '; }
else { $label = '<b>'.$label.'</b>: '; }
}
if ($gettype == 'string' || $gettype == 'integer' || $gettype == 'double' || $gettype == 'boolean') {
if ($CLI) { echo $label . $data . "\n"; }
else { echo $label . $data . "<br/>"; }
}
else {
if ($CLI) { echo $label . print_r($data,1) . "\n"; }
else { echo $label . "<pre>".print_r($data,1)."</pre>"; }
}
}
// Usage
out('Hello world!');
$var = 'Hello Stackoverflow!';
out($var, 'Label');
Not very "elegant" and kinda a waste, but if you really care what the code looks like you could make your own fancy flag and then do a str_replace.
Example:<br />
$myoutput = "After this sentence there is a line break.<b>.|..</b> Here is a new line.";<br />
$myoutput = str_replace(".|..","<br />",$myoutput);<br />
or
how about:<br />
$myoutput = "After this sentence there is a line break.<b>E(*)3</b> Here is a new line.";<br />
$myoutput = str_replace("E(*)3","<br />",$myoutput);<br />
I call the first method "middle finger style" and the second "goatse style".
Because you are outputting to the browser, you have to use <br/>. Otherwise there is \n and \r or both combined.
Well, as with any language there are several ways to do it.
As previous answerers have mentioned, "<br/>" is not a linebreak in the traditional sense, it's an HTML line break. I don't know of a built in PHP constant for this, but you can always define your own:
// Something like this, but call it whatever you like
const HTML_LINEBREAK = "<br/>";
If you're outputting a bunch of lines (from an array of strings for example), you can use it this way:
// Output an array of strings
$myStrings = Array('Line1','Line2','Line3');
echo implode(HTML_LINEBREAK,$myStrings);
However, generally speaking I would say avoid hard coding HTML inside your PHP echo/print statements. If you can keep the HTML outside of the code, it makes things much more flexible and maintainable in the long run.
\n didn't work for me. the \n appear in the bodytext of the email I was sending.. this is how I resolved it.
str_pad($input, 990); //so that the spaces will pad out to the 990 cut off.