Im new to PHP and I can't figure out what the rules are for using the echo function. For example, if I need to echo a large block of css/js, do I need to add echo to each line of text or is there a way to echo a large block of code with a single echo?
When I try to echo a big block of code like this one, I get an error:
if (is_single()) {
echo '<link type="text/css" rel="stylesheet" href="http://jotform.com/css/styles/form.css"/><style type="text/css">
.form-label{
width:150px !important;
}
.form-label-left{
width:150px !important;
}
.form-line{
padding:10px;
}
.form-label-right{
width:150px !important;
}
body, html{
margin:0;
padding:0;
background:false;
}
.form-all{
margin:0px auto;
padding-top:20px;
width:650px !important;
color:Black;
font-family:Verdana;
font-size:12px;
}
</style>
<link href="http://jotform.com/css/calendarview.css" rel="stylesheet" type="text/css" />
<script src="http://jotform.com/js/prototype.js" type="text/javascript"></script>
<script src="http://jotform.com/js/protoplus.js" type="text/javascript"></script>
<script src="http://jotform.com/js/protoplus-ui.js" type="text/javascript"></script>
<script src="http://jotform.com/js/jotform.js?v3" type="text/javascript"></script>
<script src="http://jotform.com/js/location.js" type="text/javascript"></script>
<script src="http://jotform.com/js/calendarview.js" type="text/javascript"></script>
<script type="text/javascript">
JotForm.init(function(){
$('input_6').hint('ex: myname#example.com');
});
</script>';
}else {
}
Is there a better way to echo large blocks of code without a lot of work (adding echo to each line for example)?
Heredoc syntax can be very useful:
// start the string with 3 <'s and then a word
// it doesn't have to be any particular string or length
// but it's common to make it in all caps.
echo <<< EOT
in here is your string
it has the same variable substitution rules
as a double quoted string.
when you end it, put the indicator word at the
start of the line (no spaces before it)
and put a semicolon after it
EOT;
One option is to get out of the php block and just write HTML.
With your code, after the opening curly brace of your if statement, end the PHP:
if (is_single()) { ?>
Then remove the echo ' and the ';
After all your html and css, before the closing }, write:
<? } else {
If the text you want to write to the page is dynamic, it gets a little trickier, but for now this should work fine.
Check out heredoc. Example:
echo <<<EOD
Example of string
spanning multiple lines
using heredoc syntax.
EOD;
echo <<<"FOOBAR"
Hello World!
FOOBAR;
The is also nowdoc but no parsing is done inside the block.
echo <<<'EOD'
Example of string
spanning multiple lines
using nowdoc syntax.
EOD;
Echoing text that contains line breaks is fine, and there's no limit on the amount of text or lines you can echo at once (save for available memory).
The error in your code is caused by the unescaped single quotes which appear in the string.
See this line:
$('input_6').hint('ex: myname#example.com');
You'd need to escape those single quotes in a PHP string whether it's a single line or not.
There is another good way to echo large strings, though, and that's to close the PHP block and open it again later:
if (is_single()) {
?>
<link type="text/css" rel="stylesheet" href="http://jotform.com/css/styles/form.css"/><style type="text/css">
.form-label{
width:150px !important;
}
.form-label-left{
width:150px !important;
}
.form-line{
padding:10px;
}
.form-label-right{
width:150px !important;
}
body, html{
margin:0;
padding:0;
background:false;
}
.form-all{
margin:0px auto;
padding-top:20px;
width:650px !important;
color:Black;
font-family:Verdana;
font-size:12px;
}
</style>
<link href="http://jotform.com/css/calendarview.css" rel="stylesheet" type="text/css" />
<script src="http://jotform.com/js/prototype.js" type="text/javascript"></script>
<script src="http://jotform.com/js/protoplus.js" type="text/javascript"></script>
<script src="http://jotform.com/js/protoplus-ui.js" type="text/javascript"></script>
<script src="http://jotform.com/js/jotform.js?v3" type="text/javascript"></script>
<script src="http://jotform.com/js/location.js" type="text/javascript"></script>
<script src="http://jotform.com/js/calendarview.js" type="text/javascript"></script>
<script type="text/javascript">
JotForm.init(function(){
$('input_6').hint('ex: myname#example.com');
});
</script>
<?php
}else {
}
Or another alternative, which is probably better for readability, is to put all that static HTML into another page and include() it.
Man, PHP is not perl!
PHP can just escape from HTML :)
http://www.php.net/manual/en/language.basic-syntax.phpmode.php
if (is_single()) {
//now we just close PHP tag
?>
</style>
<script>
<blah blah blah>
<?php
//open it back. here is your PHP again. easy!
}
?>
I wonder why such many people stuck to ugly heredoc.
Your problem is actually caused by:
$('input_6').hint('ex: myname#example.com');
You need to escape the single quotes to be \'
However: Using a Heredoc is a much better idea, as it will be much cleaner overall.
To expand on #hookedonwinter's answer, here's an alternate (cleaner, in my opinion) syntax:
<?php if (is_single()): ?>
<p>This will be shown if "is_single()" is true.</p>
<?php else: ?>
<p>This will be shown otherwise.</p>
<?php endif; ?>
Just break out where you need to.
<html>
(html code)
<?php
(php code)
?>
(html code)
</html>
Do not use shortened-form. <? conflicts with XML and is disabled by default on most servers.
I prefer to concatenate multiple Strings together. This works either for echo AND for variables.
Also some IDEs auto-initialize new lines if you hit enter.
This Syntax also generate small output because there are much less whitespaces in the strings.
echo ''
.'one {'
.' color: red;'
.'}'
;
$foo = ''
.'<h1>' . $bar . '</h1>' // insert value of bar
.$bar // insert value of bar again
."<p>$bar</p>" // and again
."<p>You can also use Double-Quoted \t Strings for single lines. \n To use Escape Sequences.</p>"
// also you can insert comments in middle, which aren't in the string.
.'<p>Or to insert Escape Sequences in middle '."\n".' of a string</p>'
;
Normally i start with an empty string and then append bit by bit to it:
$foo = '';
$foo .= 'function sayHello()'
.' alert( "Hello" );'
."}\n";
$foo .= 'function sum( a , b )'
.'{'
.' return a + b ;'
."}\n";
(Please stop Posts like "uh. You answer to an five jears old Question." Why not? There are much people searching for an answer. And what's wrong to use five year old ideas? If they don't find "their" solution they would open a new Question. Then the first five answers are only "use the search function before you ask!" So. I give you another solution to solve problems like this.)
$num = 5;
$location = 'tree';
$format = 'There are %d monkeys in the %s';
echo sprintf($format, $num, $location);
You can achieve that by printing your string like:
<?php $string ='here is your string.'; print_r($string); ?>
Related
I want to include a php script in a css file:
<?php
$str = "5px";
echo $str;
?>
and then
.header {
font-size: $str;
}
Is it possible?
No, not like that. CSS isn't a programming language, and has NOTHING to do with PHP.
You can, however, have PHP generate the CSS:
html:
<link rel="stylesheet" href="foo.php" ... />
foo.php
<?php
header('Content-type: text/css');
$str = '5px';
?>
.header {
font-size: '<?php echo $str; ?>';
}
Note that since you'r GENERATING css, you have to make absolutely SURE that whatever PHP outputs will be valid for the context the output is going into. It is very easy to output something that'll be a CSS syntax error and kill the rest of the CSS file.
This might be a easy one, i don't know. I'm trying to add a line sapce in css output. Here is the code
echo '<style type="text/css">\n';
echo get_option('custom_css');
echo '</style>';
But when i do this output comes as
<style type="text/css">\n.button{
margin-bottom: 22px;
}</style>
EDITED
Since this is inside style tag it won't add empty or new line i think.I want to have a new line between style tags. So tags will be in separate line, no other style will be collapsed with the same line to the style tag. How to do it?
IT should Look like this
<style type="text/css">
.button{
margin-bottom: 22px;
}
</style>
Just put your string in double quotes. Single quotes aren't parsed for looking special chars in it.
echo "<style type=\"text/css\">\n";
echo get_option('custom_css');
echo '</style>';
For example.
Or like other guys said - concatenate it with PHP_EOL constant
Try PHP_EOL instead of \n
echo '<style type="text/css">'.PHP_EOL;
  is your friend. Add it whereever you want the space.
Try like
echo '<style type="text/css"><br/>';
echo get_option('custom_css');
echo '<br/></style>';
Since this is inside style tag it won't add empty space i think.I want
to have a space between style tags. How to do it?
Add inside where you want the space to occur.
i got another problem removing linebreaks from within a token in a template file - the template i have to parse could look something like this:
<html>
<style>
body { color: black }
div {
background-color:#fff;
}
<!-- i need to remove the line breaks within {_WP_token[*]} for parsing //-->
<h4>{_WP_token[id="42";class="foo"; style="border:4px solid
green;padding:20px"; onclick="(this.value=confirm('foo'));"]}</h4>
<script>
function() {
console.log('my foo is my castle');
}
</script>
I tried myself without making the break-through. i just succeeded in creating a greedy one, which eats up the first half of the token - here it is:
preg_replace("/(\{_(.*?)(.*\s))/ix", "[LB REMOVED]", $htmlTemplate);
returns
<html>
<style>
body { color: black }
div {
background-color:#fff;
}
<!-- it just ate up the first half of my token ! //-->
<h4>[LB_REMOVED]green;padding:20px"; onclick="(this.value=confirm('foo'));"]}</h4>
<script>
function() {
console.log('my foo is my castle');
}
</script>
i made a fiddle here: http://www.phpliveregex.com/p/2EZ
thank you very much in advance.
best regards,
Lupo
Try:
$newString = preg_replace("/[\n\r]/","[LB_REMOVED]", $originalString);
I am not sure I understand you correctly. If you want to change
<h4>{_WP_token[id="42";class="foo"; style="border:4px solid
green;padding:20px"; onclick="(this.value=confirm('foo'));"]}</h4>
into
<h4>{_WP_token[id="42";class="foo"; style="border:4px solid green;padding:20px"; onclick="(this.value=confirm('foo'));"]}</h4>
Then you can use this
\{_(.*)[\r\n]+
and replace with $1, See it on Regexr
preg_replace("/\{_(.*)[\r\n]+/", "$1", $htmlTemplate);
I removed all your modifiers, since you do not use them. See Modifiers doc
I have an array of various input boxes, that when filled, fills up the database with information. Then, from another file, I take the information and print it out to the screen.
What I want to do is to put a symbol in front of each line, however using something like .style br {}; doesn't seem to work.
Reading the from MySQL, using Wordpress if that matters.
EDIT:
I was asked to post how I want it to look like. I think this is pretty straight-forward, but here it is anyway:
# Entry1
# Entry2
# Entry3
EDIT #2:
I would prefer it to be in CSS, if that's not possible, then PHP. Javascript would be the last solution that I want.
I have tried the following and it didn't work at all:
.myform.lines br {
border-bottom: 1px dashed #000000;
background-color: #ffffff;
display: block;
}
Hi have a look at Can you target <br /> with css?
I tried the following html page:
<html><head><title>Test</title>
</head><body>
<script type="text/javascript" src="jquery-1.7.2.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('br').replaceWith('<br># ');
});
</script>
hi<br>
there<br>
testing<p>
again<p>
</body></html>
This results in
hi
# there
# testing
again
Here is some more code that also does basically the same thing - it adds a symbol (#) at the start of each line (assuming new lines follow a br).
<html><head><title>test2</title>
<script type="text/javascript">
function replaceLineBreaksWithHorizontalRulesInElement(element)
{
elems = element.getElementsByTagName( 'br' );
for ( var i = 0; i < elems.length; i ++ )
{
br = elems.item( i );
txt = document.createTextNode("# ");
br.parentNode.insertBefore(txt, br.nextSibling);
}
}
</script>
</head>
<body onload="replaceLineBreaksWithHorizontalRulesInElement(document)">
testing<br>
one<br>
two<br>
three<br>
four<br>
five<p>
six<p>
</body></html>
Note that this does work in both firefox and internet explorer giving the same results. If you remove the space however then firefox shows a space anyway, and internet explorer shows no space. I think this won't be an issue for you though, since you want the space.
How about
.mySelector:before { content: '#'; }
I need to change the CSS on a webpage based on a query string in the URL... but I'm new to PHP and havn't been able to find sufficient examples on how to do it.
Basically when a user clicks on a menu link, and is then sent to an "aboutUs.php" page, I need the CSS on the aboutUs.php page to change based on the string query.
If I understand what you want correctly:
if (isset($_GET['query'])){
$query = $_GET['query'];
}else{
$query = NULL;
}
Then something like this:
if ($query == 'x'){
echo "
<style>
Whatever style you need...
</style>
";
}elseif ($query == 'y'){
echo "
<style>
Whatever other style you need...
</style>
";
}else{
echo "
<style>
Whatever default style you need...
</style>
";
}
Of course you can echo stylesheet link instead of style tags, but the logic is the same.
You can change your style.css to style.php which you can load in the page as a style sheet.
You need to include a header type in your php file:
<?php
header("Content-type: text/css");
?>
and then generate the content dynamically.
In hope I didn't missunderstand the question. This can help you change the content of the css file.
If you have multiple css files and you want to import one of them depending on the parameters to aboutus.php, that's a different story.
In the head of your program (where you would include the css stylesheets) do a simple if else:
if (isset($REQUEST['query_string'])) {?>
stylesheet link
<?php } else { ?>
stylesheet link 2
<?php } ?>
You can save the selected CSS into a cookie:
if (isset($_GET['setstyle'])) {
setcookie('style', $_GET['setstyle'], time()+60*60*24*30, '/');
}
The Style can then be read like this: $_COOKIE['style'].
http://example.com/?setstyle=black -> Style is set to „black“
not very pretty solution but for example something like this would work
<? php
if($str=="main"){
echo '<link rel="stylesheet" type="text/css" media="all" href="/css/main.css" />'
}
else if($str=="other"){
echo '<link rel="stylesheet" type="text/css" media="all" href="/css/other.css" />'
}
?>
be careful with doing something like:
<link rel="stylesheet" type="text/css" media="all" href="/css/$str.css" />
it is not very secure way, unless you do for example an array with possible values, something like
$possibleCss = array("main", "other");
if(in_array($str, $possibleCss){
<link rel="stylesheet" type="text/css" media="all" href="/css/$str.css" />
}
You need to create a php file with header text/css, this file you can call with get parameters.
example:
$style = $_GET["style"];
header("Content-type: text/css");
if($style=="blue")
echo ".class{background-color:blue;}";
else
echo ".class{background-color:white;}";
Call the css with get parameters
<link rel="stylesheet" type="text/css" href="style_file.php?style=blue" />
Knowing the purpose of your question, from here, I would put all of your common css in on stylesheet, and simply call out specific display properties for the elements you care about. Make all of your elements display: none in your main stylesheet.
<link type="text/css" rel="stylesheet" href="mainStyleSheet.css" />
<style type="text/css">
<?php
if (isset($_GET['section'])){
// Sanitize
$section = preg_replace('/[^a-zA-Z]/', $_GET['section']);
echo '#' . $section . ' { display: block; }';
}
?>
</style>
In this case, section is a parameter, set to ourMisson, ourHistory, etc., called like this:
http://beta.***.com/aboutUs.php?section=ourMission