I have a string 90001 90002. I need to see which html special char is represented in the empty space. (It could be an empty space - or it could be a textual line-break masquerading as a space in HTML see here. Maybe other possibilities that I'm not aware of..)
I would like to echo a string and show the empty spaces as html char (e.g. $result = "90001 90002").
I've tried using html_entities but that doesn't cover spaces. Also neither does htmlspecialchars.
How would I go about doing this?
If possible I would like a purely PHP & html solution. If necessary - CSS. And if impossible otherwise, javascript will have to do..
Just an out-of-box thinking. I had the same issue but looked into using JavaScript's encodeURIComponent() function:
$(function () {
$("div").html(function () {
return encodeURIComponent($(this).html());
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>90001 90002</div>
Used jQuery as I am kinda lazy. You can do the same in JavaScript this way:
<div>90001 90002</div>
<script>
var div = document.querySelector("div");
div.innerHTML = encodeURIComponent(div.innerHTML);
</script>
Just letting you know that this is better to handle in client side than in the server side.
Update 2: Getting the HTML content and updating the text of the HTML:
$(function () {
$("div").text(function () {
return $(this).html().replace(/[\u00A0-\u9999<>\&]/gim, function(i) {
return '&#'+i.charCodeAt(0)+';';
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>90001—90002</div>
Something like this...
<?php
$mystring = "90001 90002";
$mystring = str_replace(" "," ",$mystring);
echo $mystring;
?>
I hope it helps
function removeWhiteSpace($text)
{
$text = preg_replace('/[\t\n\r\0\x0B]/', '', $text);
$text = preg_replace('/([\s])\1+/', ' ', $text);
$text = trim($text);
return $text;
}
Editing the Answer :
if you need to do it using PHP , Use urlencode function , which would hep to resolve it
<?php
$query_string = 'foo=' . urlencode($foo) . '&bar=' . urlencode($bar);
echo '<a href="mycgi?' . htmlentities($query_string) . '">';
?>
But they have set backs which is mentioned in the notes section of the documentation.
http://php.net/manual/en/function.urlencode.php
You can also use functions like htmlentities,rawurlencode in php .
if you want to use it in javascript , You can use escape function.
https://www.w3schools.com/jsref/jsref_escape.asp
I want to remove %, +, ascii codes from url.
Example:
From
http://prexprint.com/Laminated%20Business%20Cards
to
http://prexprint.com/Laminated Business Cards
Browser will always render in URL spaces with %20 we can't change it.
if you want to change it http://prexprint.com/Laminated Business Cards than instead of this make your url
http://prexprint.com/Laminated+Business+Cards
or
http://prexprint.com/LaminatedBusinessCards
$x = 'http://prexprint.com/Laminated%20Business%20Cards';
$y =str_replace('%20',' ',$x);
echo $y;
or use
<?php echo rawurldecode('http://prexprint.com/Laminated%20Business%20Cards'); ?>
URLs in address bar cannot be with spaces. You can use URL Rewrite such that you can make your URL look like this http://prexprint.com/Laminated-Business-Cards. Even if you place a link like this http://prexprint.com/Laminated Business Cards, the browsers will automatically replaces the spaces with '%20'
There you go with JS:
var orgUrl = 'http://prexprint.com/Laminated%20Business%20Cards';
var reqUrl = decodeURI(orgUrl);
console.log(reqUrl);
Edit:
var orgUrl = 'http://prexprint.com/Laminated%20Business%20Cards';
var reqUrl = decodeURI(orgUrl)
reqUrl = reqUrl.replace(/\ /g, '-');
console.log(reqUrl)
window.location.href = reqUrl
Use urldecode function of PHP
<?php
echo urldecode('http://prexprint.com/Laminated%20Business%20Cards');
?>
You can use
<?php echo urldecode('http://prexprint.com/Laminated%20Business%20Cards'); ?>
You should have the urls encoded, for compatability issues.
"If it ain't broke, don't fix it."
The following works just fine:
var sFirstText=<?php include("first2.html"); ?>;
when first2.html looks like this INCLUDING the double quotes:
"<p>sentence one</p><p>sentence two</p>"
However, if first2.html looks like:
"<p>sentence one</p>
<p>sentence two</p>"
I get an unterminated string literal message. I hope to figure out how I can include the html without first having to remove the carriage return/line feed sequences.
Also, if I remove the double quotes and do:
var sFirstText="<?php include("first2.html"); ?>";
that won't work, returning a message I haven't yet been able to comprehend.
Basically I want to get simple html formatting into a field without having to remove the cr/lf sequences.
Try using a \ at the end of the line to continue the string to the next line.
Javascript can not handle those newlines. You might wanna open the file, read contents and replace those with empty spaces instead.
Also, while getting the source content, you will need to escape the type of quote you're using to wrap it.
Here's what I would do.
function contents($file, $wrappingQuote='\'') {
$fh = fopen($file,'r');
$contents = fread($fh,filesize($file));
fclose($fh);
echo preg_replace('~\'~','\\'.$wrappingQuote,preg_replace('~\r?\n~','',$contents));
}
(…)
var str = '<?php contents('first2.html') ?>';
// or
var str = "<?php contents('first2.html','"') ?>";
I am trying to get the full path of an uploaded file. The php code is like this:
<?php
$destination_path = getcwd() . DIRECTORY_SEPARATOR;
$result = 0;
$target_path = $destination_path . basename($_FILES['thefile']['name']);
if(#move_uploaded_file($_FILES['thefile']['tmp_name'],*$target_path)) {
$result = 1;
}
?>
<script language="javascript" type="text/javascript">
//d = '<?php echo basename( $_FILES['thefile']['name']); ?>';
d = '<?php echo $target_path; ?>';
window.top.window.phpUpload(d);
</script>
I can open the json file with the rem'd out line but I need the path to return it at session end. Testing with an alert the full path is shown without slashes and the initial letter 'n' of the filename missing ...
Any help much appreciated.
(Click on Names then open nset.json at this test site to see what I'm trying to do)
You are assumingly using this on Windows, where DIRECTORY_SEPARATOR is a backslash. If the filename starts with a n then your Javascript code will end up like this:
d = '..\path\nameoffile.txt';
Javascript unlike PHP will interpret \n in single quoted strings.
The solution to your dilemma is either not using DIRECTORY_SEPARATOR, or outputting a correctly escaped Javascript string:
d = <?php echo json_encode($target_path); ?>;
Do you mean the full path to the file on the client's machine? JavaScript security will not reveal that. It will just send the actual file name to the server.
This question already has answers here:
How do I pass variables and data from PHP to JavaScript?
(19 answers)
Closed 8 years ago.
The community reviewed whether to reopen this question 1 year ago and left it closed:
Original close reason(s) were not resolved
What is the easiest way to encode a PHP string for output to a JavaScript variable?
I have a PHP string which includes quotes and newlines. I need the contents of this string to be put into a JavaScript variable.
Normally, I would just construct my JavaScript in a PHP file, à la:
<script>
var myvar = "<?php echo $myVarValue;?>";
</script>
However, this doesn't work when $myVarValue contains quotes or newlines.
Expanding on someone else's answer:
<script>
var myvar = <?php echo json_encode($myVarValue); ?>;
</script>
Using json_encode() requires:
PHP 5.2.0 or greater
$myVarValue encoded as UTF-8 (or US-ASCII, of course)
Since UTF-8 supports full Unicode, it should be safe to convert on the fly.
Note that because json_encode escapes forward slashes, even a string that contains </script> will be escaped safely for printing with a script block.
encode it with JSON
function escapeJavaScriptText($string)
{
return str_replace("\n", '\n', str_replace('"', '\"', addcslashes(str_replace("\r", '', (string)$string), "\0..\37'\\")));
}
I have had a similar issue and understand that the following is the best solution:
<script>
var myvar = decodeURIComponent("<?php echo rawurlencode($myVarValue); ?>");
</script>
However, the link that micahwittman posted suggests that there are some minor encoding differences. PHP's rawurlencode() function is supposed to comply with RFC 1738, while there appear to have been no such effort with Javascript's decodeURIComponent().
The paranoid version: Escaping every single character.
function javascript_escape($str) {
$new_str = '';
$str_len = strlen($str);
for($i = 0; $i < $str_len; $i++) {
$new_str .= '\\x' . sprintf('%02x', ord(substr($str, $i, 1)));
}
return $new_str;
}
EDIT: The reason why json_encode() may not be appropriate is that sometimes, you need to prevent " to be generated, e.g.
<div onclick="alert(???)" />
<script>
var myVar = <?php echo json_encode($myVarValue); ?>;
</script>
or
<script>
var myVar = <?= json_encode($myVarValue) ?>;
</script>
Micah's solution below worked for me as the site I had to customise was not in UTF-8, so I could not use json; I'd vote it up but my rep isn't high enough.
function escapeJavaScriptText($string)
{
return str_replace("\n", '\n', str_replace('"', '\"', addcslashes(str_replace("\r", '', (string)$string), "\0..\37'\\")));
}
Don't run it though addslashes(); if you're in the context of the HTML page, the HTML parser can still see the </script> tag, even mid-string, and assume it's the end of the JavaScript:
<?php
$value = 'XXX</script><script>alert(document.cookie);</script>';
?>
<script type="text/javascript">
var foo = <?= json_encode($value) ?>; // Use this
var foo = '<?= addslashes($value) ?>'; // Avoid, allows XSS!
</script>
You can insert it into a hidden DIV, then assign the innerHTML of the DIV to your JavaScript variable. You don't have to worry about escaping anything. Just be sure not to put broken HTML in there.
You could try
<script type="text/javascript">
myvar = unescape('<?=rawurlencode($myvar)?>');
</script>
Don’t. Use Ajax, put it in data-* attributes in your HTML, or something else meaningful. Using inline scripts makes your pages bigger, and could be insecure or still allow users to ruin layout, unless…
… you make a safer function:
function inline_json_encode($obj) {
return str_replace('<!--', '<\!--', json_encode($obj));
}
htmlspecialchars
Description
string htmlspecialchars ( string $string [, int $quote_style [, string $charset [, bool $double_encode ]]] )
Certain characters have special significance in HTML, and should be represented by HTML entities if they are to preserve their meanings. This function returns a string with some of these conversions made; the translations made are those most useful for everyday web programming. If you require all HTML character entities to be translated, use htmlentities() instead.
This function is useful in preventing user-supplied text from containing HTML markup, such as in a message board or guest book application.
The translations performed are:
* '&' (ampersand) becomes '&'
* '"' (double quote) becomes '"' when ENT_NOQUOTES is not set.
* ''' (single quote) becomes ''' only when ENT_QUOTES is set.
* '<' (less than) becomes '<'
* '>' (greater than) becomes '>'
http://ca.php.net/htmlspecialchars
I'm not sure if this is bad practice or no, but my team and I have been using a mixed html, JS, and php solution. We start with the PHP string we want to pull into a JS variable, lets call it:
$someString
Next we use in-page hidden form elements, and have their value set as the string:
<form id="pagePhpVars" method="post">
<input type="hidden" name="phpString1" id="phpString1" value="'.$someString.'" />
</form>
Then its a simple matter of defining a JS var through document.getElementById:
<script type="text/javascript" charset="UTF-8">
var moonUnitAlpha = document.getElementById('phpString1').value;
</script>
Now you can use the JS variable "moonUnitAlpha" anywhere you want to grab that PHP string value.
This seems to work really well for us. We'll see if it holds up to heavy use.
If you use a templating engine to construct your HTML then you can fill it with what ever you want!
Check out XTemplates.
It's a nice, open source, lightweight, template engine.
Your HTML/JS there would look like this:
<script>
var myvar = {$MyVarValue};
</script>