$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.
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);
Is there a function that returns HTML break, <br /> when in HTML and PHP_EOL when in CLI?
so that if I code something like:
echo "error is" . appropriateEOL();
will return the appropriate line break. I know how to code appropriateEOL(), I just wonder if there is a built in function.
I am using zf2.
There's nothing built-in to do what you're asking. But it would be trivial to set it up yourself.
if (PHP_SAPI == 'cli') {
define("LINE_BREAK", PHP_EOL);
}
else {
define("LINE_BREAK", "<br/>");
}
Now just use this LINE_BREAK constant.
Though it might be better to stick with non-html in your code and use PHP_EOL, and then run your output through nl2br() before displaying output in your HTML templates.
The following PHP function outputs JS:
function dothething( $data ){
$res = "
<div id=\"blah\">
Here's some stuff, ". $data['name'] ."
</div>";
echo "$('#container').html('". $res ."');";
}
This function is called via jQuery's $.ajax(), using dataType: 'script' ... so whatever is echoed runs like a JS function. There's more to it of course, but my question has to do with encoding. The ajax will fail when $res contains newlines or apostrophes. So adding this above the echo seems to be working for now:
$res = str_replace("\n", "\\n", addslashes($res));
Is this the best way to format the PHP variable $res to yield valid javascript for ajax?
Is there anything else I should add in there?
In your case I would use json_encode() over anything else:
echo "$('#container').html(" . json_encode($res) . ");";
When applied to a string value, it will automatically encapsulate it with double quotes and escape anything inside that would otherwise cause a parse error.
Try this,
if(count($result)>0) {
$status = 0;
} else {
$status = 1;
}
$json['status'] = $status;
$json['result'] = $output;
print(json_encode($json));
Is there any native PHP function as highlight_string(); but for javascript ?
Or, if not, is there any PHP function (homemade) to do it?
EDIT: I want to use PHP function to COLORIZE javascript
I have had great success with GeSHi. Easy to use and integrate in your app and it supports a lot of languages.
I understand you want a Syntax Highligher written in PHP. This one (Geshi) has worked for me in the past:
http://qbnz.com/highlighter/
Yes, the PHP function highlight_string() is a native PHP function for PHP.
No.
But there are a lot of javascript libraries that do syntax-highlight on several languages,
from bash-scripting to php and javascript.
eg, like snippet (JQuery) or jQuery.Syntax (my favorite)
Over here you can find an excellent library which enables syntax highlighting in a large amount of languages using javascripts and a css class.
There is no native php function to do this, so either you have to use existing libraries or you have to write something yourself.
Fastest way - you can use also PHP function "highlight_string" with a little trick
(capture function output and remove leading/trailing PHP tags):
$source = '... some javascript ...';
// option 1 - pure JS code
$htmlJs = highlight_string('<?php '.$source.' ?>', true);
$htmlJs = str_replace(array('<?php ', ' ?>'), array('', ''), $htmlJs);
// option 2 - when mixing up with PHP code inside of JS script
$htmlJs = highlight_string('START<?php '.$source.' ?>END', true);
$htmlJs = str_replace(array('START<span style="color: #0000BB"><?php </span>', ' ?>END'), array('', ''), $htmlJs);
// check PHP INI setting for "highlight.keyword" (#0000BB) - http://www.php.net/manual/en/misc.configuration.php#ini.syntax-highlighting
No native function, but rather than using a full stack library just to highlight some javascript you can use this single function :
function format_javascript($data, $options = false, $c_string = "#DD0000", $c_comment = "#FF8000", $c_keyword = "#007700", $c_default = "#0000BB", $c_html = "#0000BB", $flush_on_closing_brace = false)
{
if (is_array($options)) { // check for alternative usage
extract($options, EXTR_OVERWRITE); // extract the variables from the array if so
} else {
$advanced_optimizations = $options; // otherwise carry on as normal
}
#ini_set('highlight.string', $c_string); // Set each colour for each part of the syntax
#ini_set('highlight.comment', $c_comment); // Suppression has to happen as some hosts deny access to ini_set and there is no way of detecting this
#ini_set('highlight.keyword', $c_keyword);
#ini_set('highlight.default', $c_default);
#ini_set('highlight.html', $c_html);
if ($advanced_optimizations) { // if the function has been allowed to perform potential (although unlikely) code-destroying or erroneous edits
$data = preg_replace('/([$a-zA-z09]+) = \((.+)\) \? ([^]*)([ ]+)?\:([ ]+)?([^=\;]*)/', 'if ($2) {' . "\n" . ' $1 = $3; }' . "\n" . 'else {' . "\n" . ' $1 = $5; ' . "\n" . '}', $data); // expand all BASIC ternary statements into full if/elses
}
$data = str_replace(array(') { ', ' }', ";", "\r\n"), array(") {\n", "\n}", ";\n", "\n"), $data); // Newlinefy all braces and change Windows linebreaks to Linux (much nicer!)
$data = preg_replace("/(^[\r\n]*|[\r\n]+)[\s\t]*[\r\n]+/", "\n", $data); // Regex identifies all extra empty lines produced by the str_replace above. It is quicker to do it like this than deal with a more complicated regular expression above.
$data = str_replace("<?php", "<script>", highlight_string("<?php \n" . $data . "\n?>", true));
$data = explode("\n", str_replace(array("<br />"), array("\n"), $data));
# experimental tab level highlighting
$tab = 0;
$output = '';
foreach ($data as $line) {
$lineecho = $line;
if (substr_count($line, "\t") != $tab) {
$lineecho = str_replace("\t", "", trim($lineecho));
$lineecho = str_repeat("\t", $tab) . $lineecho;
}
$tab = $tab + substr_count($line, "{") - substr_count($line, "}");
if ($flush_on_closing_brace && trim($line) == "}") {
$output .= '}';
} else {
$output .= str_replace(array("{}", "[]"), array("<span style='color:" . $c_string . "!important;'>{}</span>", "<span style='color:" . $c_string . " !important;'>[]</span>"), $lineecho . "\n"); // Main JS specific thing that is not matched in the PHP parser
}
}
$output = str_replace(array('?php', '?>'), array('script type="text/javascript">', '</script>'), $output); // Add nice and friendly <script> tags around highlighted text
return '<pre id="code_highlighted">' . $output . "</pre>";
}
Usage :
echo format_javascript('console.log("Here is some highlighted JS code using a single function !");') ;
Credit :
http://css-tricks.com/highlight-code-with-php/
Demo :
http://css-tricks.com/examples/HighlightJavaScript/
Well nice info here . Here is another nice one : http://code.google.com/p/google-code-prettify/
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');