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/
Related
I have a php variable containing some special characters, inside a Codeigniter 3 controller:
page_url = 'search=' . $expression . '&page';
In a template, I use this variable:
In the in the browser I see the characters mentioned above in this form:
posts/search?search%3Dharum%26page=2
The = sign turns to %3D, "&" to %26.
I tried page_url = urldecode($page_url); but it does not work.
How do I keep the original characters?
Please use utf8 decode and try again
echo utf8_decode(urldecode("search%3Dharum%26page=2"));
Try this decode function.
function decode($url)
{
$special = array(
'%21' => '!', '\\' => '%5C', // so on you need to define.
);
foreach($special as $key => $value)
{
$result = str_replace($key, $value, $url);
}
return $result;
}
echo decode("search=%21");
Your problem is not that easy to reproduce. The following rextester demo produces the text in the form you request, using basically your code: http://rextester.com/YTY13099
<?php
$page=2;
$expression='harum';
$page_url = 'posts/search?search=' . $expression . '&page=' . $page;
?>
resulting in
Link
Could it be that the problem is caused by that fact that the script is part of a codeigniter controller? I do not know anything about codeigniter but I can image that further processing takes place there.
i have a javascript and php code that makes an email address hard for bots to find. i have it implemented on one site thats very basic and it works perfect, however on this other site with many more elements—something seems to go awry and it wont work.
the javascript adds in the mailto: and # functions
in the php, the elements are called in and the javascript runs to complete the function when you click on it——making it like a regular mailto: function.
is there something i'm missing in terms of perhaps DOM or global elements or something?
i have this script being called in my
header.php:
<script type="text/javascript" src="javascript/scripts.js"></script>
scripts.js:
function blind(name,domain) {
str = "mailto:" + name + "#" + domain;
window.location = str;
}
emailgen.php:
function showContacts()
{
global $debe;
$return ="";
$return .="
<div>";
$contactitems = $debe->runSql("SELECT * FROM contacts ORDER BY imp");
for($i=0; $i<count($contactitems); $i++)
{
$parts = explode('#', substr($contactitems[$i][3], $pos + 0));
$return .="
<p>" . $contactitems[$i][1] . "<br />
" . $parts[0] . "#" . $parts[1] . "<br />
</p>";
}
return $return;
}
when i view the source, it seems to show up okay but for some reason the mailto: isn't calling.
viewsource of emailgen.php:
name#email.com<br />
Add a single quote after $parts[0] . ":
" . $parts[0] . "#" . $parts[1] . "<br />
I'm currently using the following method to get coordinates from GoogleMaps.
Can I possibly write this shorter/more efficient?
EDIT 21.06.2013
As of now the old Google Geocoding API is off. This is my modified code that works with the most recent version. I've updated this post, if someone stumbles over it and finds it useful.
public function getGeographicCoordinatesFromGoogle()
{
// create address string
$value = $this->address_line_1 . ' ' .
$this->postal_code . ' ' .
$this->city . ' ' .
$this->country;
$value = preg_replace('!\s+!', '+', $value);
// create request
$request = 'http://maps.googleapis.com/maps/api/geocode/xml?address=' .
$value . '&sensor=false';
// get value from xml request
$xml = file_get_contents($request);
$doc = new \DOMDocument('1.0', 'UTF-8');
#$doc->loadXML($xml);
// fetch result
$result = $doc->getElementsByTagName('lat')->item(0)->nodeValue . ',' .
$doc->getElementsByTagName('lng')->item(0)->nodeValue;
// check result
if (!preg_match('/(-?\d+\.\d+),(-?\d+\.\d+)/', $result) ) {
$result = null;
}
// assign value
$this->setGeographicCoordinates($result);
}
You can use json instead of xml. json is newer, lightweight and object orientated.
I'll recommend you to use http_build_query() instead of trying to build the SearchQuery with Regex. There are other chars which need to be escaped.
This is a quite long method. Maybe it would make sense to have one Class which only handles the communication with GoogleMaps (Class GeoBackend with methods getGeoDataForAddress(), which returns a GeoData-Object, which could be asked for Cordinates etc.)
What is the simplest and fastest way to check if string is single URL or TEXT (that might contain urls)
possible scenarios:
// successful scenario
$example[] = 'http://sub-domain.my-domain.com/folder/file.php?some=param';
// successful scenario
$example[] = '/assets/scripts/jquery.min.js?v=1.4';
// successful scenario
$example[] = 'jquery.min.js';
// this scenario should fail validation
$example[] = "http://www.domain.com welcome text\n and some other http://www.domain.com";
// this scenario should fail validation
$example[] = "scriptVar=50;";
I have tried to use native php functions like parse_url, filter_var but non of them work as expected.
UPDATE 1
To make it more clear, I'm trying to separate possible URI from script content that would be inserted as DOM element. All urls would go as SRC attribute and rest as content, example:
<script type="text/javascript" src="{$string}"></script>
<script type="text/javascript">{$string}</script>
UPDATE 2
By analysing possible content I come to conclusion that string containing white space character or semicolon mean that string could not be URI, I presume that this pattern could solve my problem:
preg_match('/[\s]|[;]/', $string);
would it cover all possible javascript/css code?
$exampleData = Array(
'http://sub-domain.my-domain.com/folder/file.php?some=param',
'/assets/scripts/jquery.min.js?v=1.4',
'<a href="/assets/scripts/jquery.min.js?v=1.4">',
'<a href="assets/scripts/jquery.min.js?v=1.4">',
'http://www.domain.com welcome text\n and some other http://www.domain.com',
);
foreach($exampleData as $example)
{
echo "Trying \"" . $example . "\" -> ";
echo (preg_match('%((http(s)?://|www\.)[^ \r\n]+|<a.+?href=(\'|")(http(s)?://|www\.|[^#])[^\4\r\n]*?\4.*?>)%i', $example)) ?
"Match" : "No match";
echo "\r\n";
}
This would produce:
Trying "http://sub-domain.my-domain.com/folder/file.php?some=param" -> Match
Trying "/assets/scripts/jquery.min.js?v=1.4" -> No match
Trying "<a href="/assets/scripts/jquery.min.js?v=1.4">" -> Match
Trying "<a href="assets/scripts/jquery.min.js?v=1.4">" -> Match
Trying "http://www.domain.com welcome text\n and some other http://www.domain.com" -> Match
Update:
After reading your last update. If you want to parse HTML. Use a DOM-parser like:
http://simplehtmldom.sourceforge.net/
Example:
include_once('simple_html_dom.php');
$dom = file_get_html('http://www.stackoverflow.com/');
foreach($dom->find('script') as $scriptElement)
{
if(strlen(trim($scriptElement->src)) > 0)
{
// Script with URI set
echo "<strong>Found script with URI</strong>";
echo "<p>" . $scriptElement->src . "</p>";
}
else
{
// Script with content
echo "<strong>Found script with content</strong>";
echo("<p>" . nl2br(htmlspecialchars($scriptElement->innertext)) . "</p>");
}
}
Would output something like(HTML stripped):
Found script with URI
http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js
Found script with URI
http://sstatic.net/js/master.min.js?v=afc76d4deac3
Found script with content
var imagePath='http://sstatic.net/stackoverflow/img/';
var inboxUnviewedCount = -1;
...etc
This function will return true if the passed text is an URL. It is based on a regex seen here on SO.
function validate_url ($url)
{
$regex = '/^(https?|ftp):\/\/'; //protocol
$regex .= '(([a-z0-9$_\.\+!\*\'\(\),;\?&=-]|%[0-9a-f]{2})+'; //username
$regex .= '(:([a-z0-9$_\.\+!\*\'\(\),;\?&=-]|%[0-9a-f]{2})+)?'; //password
$regex .= '#)?'; //auth requires #
$regex .= '((([a-z0-9][a-z0-9-]*[a-z0-9]\.)*'; //domain segments AND
$regex .= '[a-z][a-z0-9-]*[a-z0-9]'; //top level domain OR
$regex .= '|((\d|[1-9]\d|1\d{2}|2[0-4][0-9]|25[0-5])\.){3}';
$regex .= '(\d|[1-9]\d|1\d{2}|2[0-4][0-9]|25[0-5])'; //IP address
$regex .= ')(:\d+)?'; //port
$regex .= ')(((\/+([a-z0-9$_\.\+!\*\'\(\),;:#&=-]|%[0-9a-f]{2})*)*'; //path
$regex .= '(\?([a-z0-9$_\.\+!\*\'\(\),;:#&=-]|%[0-9a-f]{2})*)'; //query string
$regex .= '?)?)?'; //path and query string optional
$regex .= '(#([a-z0-9$_\.\+!\*\'\(\),;:#&=-]|%[0-9a-f]{2})*)?'; //fragment
$regex .= '$/i';
return (preg_match($regex, $url) ? true : false);
}
You can try it here: http://www.exorithm.com/algorithm/view/validate_url
EDIT in response to comment, this function will validate URL fragments like /index.php or index.php
function validate_url_fragment ($url)
{
$regex = '/^(((\/?([a-z0-9$_\.\+!\*\'\(\),;:#&=-]|%[0-9a-f]{2})*)*'; //path
$regex .= '(\?([a-z0-9$_\.\+!\*\'\(\),;:#&=-]|%[0-9a-f]{2})*)'; //query string
$regex .= '?)?)?'; //path and query string optional
$regex .= '(#([a-z0-9$_\.\+!\*\'\(\),;:#&=-]|%[0-9a-f]{2})*)?'; //fragment
$regex .= '$/i';
return (preg_match($regex, $url) ? true : false);
}
if (validate_url_fragment($url) || validate_url($url)) {
//is url
} else {
//not url
}
(note that the empty string is valid, so you may want a special case for that)
filter_var should do what you want for a single URL:
<?php
$safe_url = filter_var( $unsafe_url, FILTER_SANITIZE_URL );
?>
$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.