Replace Certain Strings With PHP Variables - php

In my website I have certain preset variables such as the page title, year/time, and etc.
For example in my title I would use
<title> <?php echo $TITLE; ?> </title>
However, how would I make it so typing something like..
<title> [TITLE] </title>
Will produce the same result?

It's recommended that you use the PHP tags for many reasons, including performance and stability. If you want to do less typing you could use the shorthand for echoing variables: <?= $TITLE ?>.
If you're using a PHP version prior to 5.4 you might have to enable short_open_tags in your configuration. After version 5.4 these tags are always available
If you're dead set on using a different syntax for your HTML, you could look into a templating language like Smarty or Dwoo

$page = str_replace('[TITLE]', $title, $page);
Replace $page with your variable. Obviously then you'd have to echo out $page to get it to show.

That effect can be accomplished with template tags in a template engine such as Smarty.

Use a PHP templating language like Mustache or Smarty.
PHP vs template engine might point you towards some other options.

Related

How can I call a php variable inside html like smarty syntax?

I wants to know if someone have an idea of how can we call a variable inside html code like if we are using the smarty template.
<?php
$var = "sometext";
?>
<html>
<body>
<?php echo $var ?>
</body>
</html>
If we are using smarty template we can do like this:
<?php
$var = "sometext";
?>
<html>
<body>
{$var}
</body>
</html>
Is that possible without using smarty templates? Thank you for help!
You can't use Smarty syntax in 'naked' PHP... that's why it's Smarty syntax.
You have three options:
Use PHP's builtin syntax, which is either <?php echo $var; ?> or <?= $var; ?> (there are good reasons not to use the second, mostly that it's difficult to comment out in PHP. You have to use HTML comments which leave remnants of PHP in your HTML source.)
Write your own templating engine which parses your template files, you can use preg_match to search for a pattern like /\{(.*?)\}/ and replace them with the variables, but beware that code replacement causes complexities. If you want to go this route, look into output buffering and regex.
Use Smarty or another templating engine you like. These libraries exist, so take advantage of them.
Note: in PHP 5.4 or newer, even if short tags are disabled, the short echo tag will work. Therefore, as long as you're not running unsupported old versions of PHP, you don't have to worry about access to it.

Is there a concise way to include php variables in HTML?

All of the text on my page has to come from a translation file, so my markup is littered with stuff like <?php echo $translation; ?>.
For just one or two calls, it's fine, but when it's all over the page, it makes things awfully verbose. Is there a more concise way to include PHP variables in the markup? I can echo a heredoc, but then it removes all the IDE features for HTML editing like automatic indentation and highlighting.
Is there a way to just do something like {$translation} instead of <?php echo $translation ?>?
You can do
<?=$translation?>
If you have activated short_open_tag in your php.ini
You could use a template engine like smarty or twig. Smarty for example is supported in an IDE like netbeans.
Use a template language, like twig, it has builtin support for internatiolzation with a simple syntax.
If you want to keep "pure" PHP, you can use <?=$translation?>, or you can use a template engine, like Smarty. There are tons of those, just find one that suits you.
This should help you http://en.wikipedia.org/wiki/Template_engine_%28web%29

What is the difference between <?= and <?php? [duplicate]

Sorry for the silly question, but I ran across code that used:
<?=$MAP_OBJECT->printOnLoad();?>
<?=$MAP_OBJECT->printMap();?>
<?=$MAP_OBJECT->printSidebar();?>
Is there anything special about <?= over <?php or just plain <??
They are shorthand of <?php echo .... ?> known as short tags. You should avoid using them because:
They seem to be turned off on some servers
They can get you in trouble in terms of security
They can create conflict with processing instructions like <?xml ... ?>
Therefore you should never use them again, also have a look at:
PHP Short Open Tag: Convenient Shortcut or Short Changing Security?
Rather than talking about whether short_open_tags is deprecated or not we should talk about the advantages and disadvantages when using short open tags:
Advantages
Using the short open tags <? along with <?= is shorter and probably easier to write than the standard opening tags <?php and <?php echo respectively. That’s quite handy when using PHP directly in a template. (That’s probably also the reason why PHP has an alternative syntax for control structures.)
Disadvantages
Requires a specific configuration
When using short open tags you are required to have short_open_tags enabled. If you or your web hosting provider decides to disable short_open_tags, your application probably won’t work any more and you can have some serious security issues. Because if short_open_tags is disabled, only the standard opening tags <?php are recognized and everything inside short opening tags is treated as plain text. (See also the blog post referenced in Sarfraz Ahmed’s answer.)
This requirement makes your PHP application less portable if you aim to write applications that are not just for you. That’a also why many recommend not to use short open tags (including the PHP manual):
Note: Using short tags should be avoided when developing applications or libraries that are meant for redistribution, or deployment on PHP servers which are not under your control, because short tags may not be supported on the target server. For portable, redistributable code, be sure not to use short tags.
As of PHP 5.4 <?= is always available, regardless of the short_open_tags option. <? on the other hand requires the option to be enabled.
Conflicts with XML processing instructions
Another issue is when using XML processing instructions like <?xml … ?>. When short_open_tags is enabled you cannot use them directly in your code but need to use PHP to output it:
If you want to use PHP in combination with XML, you can disable this option in order to use <?xml ?> inline. Otherwise, you can print it with PHP, for example: <?php echo '<?xml version="1.0"?>'; ?>.
Otherwise PHP will choke on the xml in <?xml.
Now some last words about the deprecation: Currently short_open_tags is not deprecated. Otherwise the manual would state that explicitly. Additionally, Rasmus Lerdorf, inventor of PHP, wrote in a reply on the question “Is it true that short_open_tag is deprecated in PHP 6?” on the internals mailing list that there were several reasons not to remove short_open_tags in PHP 6:
Which is one of the reasons we decided not to remove them in PHP 6.
<?= is a short tag that is pretty much equivalent to:
<?php echo
As of PHP 5.4, this syntax is always available, but in earlier versions of PHP, it needs short_open_tag enabled. As for how to search for it on Stack Overflow, try code:"<?=".
It's a shorthand for <?php echo $MAP_OBJECT->printOnLoad(); ?>. Simpler way to write it when you're making PHP-based templates and things.
Be careful, though. My understanding (though I've never run into it myself) is that the shorthand version can be disabled on some servers.
<?= is not one thing. It's actually <? and then = . As #derekerdmann has mentioned, this is an unrecommended configuration.
Give the following a look:
Are PHP short tags acceptable to use?
PHP echo vs PHP short tags
Just to correct all these misguiding answers:
short open tags are not going to be removed or deprecated.
Inside short tag you cannot write like this .
<?=
$number = "5";
$sum = 15 + "5";
?>
because it will print only the first output as 5.
Inside open tag you can write like this .
<?php
echo $number ="5";
echo $sum = 15+"5";
?>
It will print both 5 and 20
its all about syntax.
adding this due to duplicate questions
aka shortags is an alternative tag for php but works only on servers that have it enabled.
It allows you to write echo like this
However it is not recommended to use them and have been suggested to be removed or deprecated in php5.4+ along with register globals, safe mode and magic quotes etc.
So though you might use them, they are not recommended.
1. They are not portable since servers must have them enabled.
2. They can lead to spaghetti code easily since you can easily integrate html in your file.
3. Special methods have to be used when mixing them with xml declaration
They are however great for making templates along with other shorthand notations for loops and conditional checks.

What is the difference between the PHP open tags “<?=” and “<?php”/“<?”?

Sorry for the silly question, but I ran across code that used:
<?=$MAP_OBJECT->printOnLoad();?>
<?=$MAP_OBJECT->printMap();?>
<?=$MAP_OBJECT->printSidebar();?>
Is there anything special about <?= over <?php or just plain <??
They are shorthand of <?php echo .... ?> known as short tags. You should avoid using them because:
They seem to be turned off on some servers
They can get you in trouble in terms of security
They can create conflict with processing instructions like <?xml ... ?>
Therefore you should never use them again, also have a look at:
PHP Short Open Tag: Convenient Shortcut or Short Changing Security?
Rather than talking about whether short_open_tags is deprecated or not we should talk about the advantages and disadvantages when using short open tags:
Advantages
Using the short open tags <? along with <?= is shorter and probably easier to write than the standard opening tags <?php and <?php echo respectively. That’s quite handy when using PHP directly in a template. (That’s probably also the reason why PHP has an alternative syntax for control structures.)
Disadvantages
Requires a specific configuration
When using short open tags you are required to have short_open_tags enabled. If you or your web hosting provider decides to disable short_open_tags, your application probably won’t work any more and you can have some serious security issues. Because if short_open_tags is disabled, only the standard opening tags <?php are recognized and everything inside short opening tags is treated as plain text. (See also the blog post referenced in Sarfraz Ahmed’s answer.)
This requirement makes your PHP application less portable if you aim to write applications that are not just for you. That’a also why many recommend not to use short open tags (including the PHP manual):
Note: Using short tags should be avoided when developing applications or libraries that are meant for redistribution, or deployment on PHP servers which are not under your control, because short tags may not be supported on the target server. For portable, redistributable code, be sure not to use short tags.
As of PHP 5.4 <?= is always available, regardless of the short_open_tags option. <? on the other hand requires the option to be enabled.
Conflicts with XML processing instructions
Another issue is when using XML processing instructions like <?xml … ?>. When short_open_tags is enabled you cannot use them directly in your code but need to use PHP to output it:
If you want to use PHP in combination with XML, you can disable this option in order to use <?xml ?> inline. Otherwise, you can print it with PHP, for example: <?php echo '<?xml version="1.0"?>'; ?>.
Otherwise PHP will choke on the xml in <?xml.
Now some last words about the deprecation: Currently short_open_tags is not deprecated. Otherwise the manual would state that explicitly. Additionally, Rasmus Lerdorf, inventor of PHP, wrote in a reply on the question “Is it true that short_open_tag is deprecated in PHP 6?” on the internals mailing list that there were several reasons not to remove short_open_tags in PHP 6:
Which is one of the reasons we decided not to remove them in PHP 6.
<?= is a short tag that is pretty much equivalent to:
<?php echo
As of PHP 5.4, this syntax is always available, but in earlier versions of PHP, it needs short_open_tag enabled. As for how to search for it on Stack Overflow, try code:"<?=".
It's a shorthand for <?php echo $MAP_OBJECT->printOnLoad(); ?>. Simpler way to write it when you're making PHP-based templates and things.
Be careful, though. My understanding (though I've never run into it myself) is that the shorthand version can be disabled on some servers.
<?= is not one thing. It's actually <? and then = . As #derekerdmann has mentioned, this is an unrecommended configuration.
Give the following a look:
Are PHP short tags acceptable to use?
PHP echo vs PHP short tags
Just to correct all these misguiding answers:
short open tags are not going to be removed or deprecated.
Inside short tag you cannot write like this .
<?=
$number = "5";
$sum = 15 + "5";
?>
because it will print only the first output as 5.
Inside open tag you can write like this .
<?php
echo $number ="5";
echo $sum = 15+"5";
?>
It will print both 5 and 20
its all about syntax.
adding this due to duplicate questions
aka shortags is an alternative tag for php but works only on servers that have it enabled.
It allows you to write echo like this
However it is not recommended to use them and have been suggested to be removed or deprecated in php5.4+ along with register globals, safe mode and magic quotes etc.
So though you might use them, they are not recommended.
1. They are not portable since servers must have them enabled.
2. They can lead to spaghetti code easily since you can easily integrate html in your file.
3. Special methods have to be used when mixing them with xml declaration
They are however great for making templates along with other shorthand notations for loops and conditional checks.

PHP Content Separation

So we all know that you should always, not only in PHP, separate code from content/design/html. (I have seen people that say the opposite here today)
I mean, you don't want one of these in bigger projects, do you?
<?php
echo '<div id="blah"><b>'
. $username . '</b>'
. $stuff . '<more HTML mixed with PHP...>';
?>
But: What is a good approach to separate code from content?
I have been using a simple template system that replaces wildcards in templates mostly.
e.g:
<div id="blah"><b>%USERNAME%</b>%STUFF% <...>
(located in a single file)
Later you can just call a function similar to GetTemplate( 'myTemplate', array ( 'USERNAME' => 'Stranger' ) );
Finally, the questions:
Is this a good way of separating code and content?
How do you do that when not working with a framework?
Is there a better way?
you should realize that PHP itself is a templating language. your
<div id="blah"><b>%USERNAME%</b>%STUFF% <...>
differs from
<div id="blah"><b><?php echo $USERNAME; ?></b><?php echo $STUFF; ?> <...>
only very superficially. granted, PHP is quite stupid with its NOTICEs and WARNINGs instead of exceptions (a point Python has over PHP), and your custom implementation may more easily allow you to e. g. throw instead of producing a fatal error (oh the joys of Smarty) if putting logic into a template somewhere turns out to be the lesser of two evils (loops). you may want to throw if the template mentions an undefined variable (PHP would issue a NOTICE), etc.
Im not fan ov additional templating languages (that replace wildcards) instead i like to keep my templates pure php so my vertion of what you have done would be:
<div id="blah"><b><?php echo $username ?></b><?php echo $stuff ?><...>
echo GetTemplate( 'myTemplate.php', array ( 'username' => 'Stranger', 'stuff' => 'Stuff' ) );
function GetTemplate($templatePath, array $vars = array())
{
extract($vars);
ob_start();
include($templatePath);
return ob_get_clean();
}
I alos combine this with helper functions/object->methods as well for example:
<?php echo link_to($name, $url); ?>
function link_to($name, $url, array $attributes = array())
{
$attributes['href'] = urlencode($url);
foreach($attributes as $attrib => $value)
{
$attributes[$attrib] = $attrib."=\"$value\"";
}
return sprintf('<a %s>%s</a>', implode(" ",$attributes), $name);
}
I generally apply helpers like these to commonly used tags/structures as well as having a general purpose html tag one that looks something like content_tag($tag, $content, $attributes); This helps me avoid a php echo for tons of attributes for random tags. I obviously dont use it for every html tag i use only for ones where it makes for better readability than a ton of echos.
As far as templating engines go i dont really see the benefit as php is templating language. As far as non-programmers/coders they have to leanr the syntax for a loop and a variable any how so i dont see how changing it to wildcards or the {} syntax of smarty adds anything.
There is a tried-and-true Templating Engine for PHP called Smarty. It isn't part of a massive framework, which is a huge plus for me. Smarty supports caching and has other performance boosts over traditional find/replace templating due to it's "compilation" of template files.
Big projects like, phpBB work using templates. Its slightly more complicated as they also allow for (for)lists, including other templates and other advanced features. You definitely want to separate code and content.
As a bonus this allows non programmers to make your html.
The approach of the Zend Framework which uses PHP as the template language (which does not add an extra parsing overhead) seems like a good apporach
Another way I really like is the approach used by limonade framework which uses ob_start() and includes to actually handle the templates

Categories