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."
So here's the problem. I have data in a MySQL DB as text. The data is inserted via mysql_real_escape_string. I have no problem with the data being displayed to the user.
At some point I want to pass this data into a javascript function called foo.
// This is a PHP block of code
// $someText is text retrieved from the database
echo "<img src=someimage.gif onclick=\"foo('{$someText}')\">";
If the data in $someText has line breaks in it like:
Line 1
Line 2
Line 3
The javascript breaks because the html output is
<img src=someimage.gif onclick="foo('line1
line2
line3')">
So the question is, how can I pass $someText to my javascript foo function while preserving line breaks and carriage returns but not breaking the code?
===========================================================================================
After using json like this:
echo "<img src=someimage.gif onclick=\"foo($newData)\">";
It is outputting HTML like this:
onclick="foo("line 1<br \/>\r\nline 2");">
Which displays the image followed by \r\nline 2");">
json_encode() is the way to go:
$json = json_encode($someText); # this creates valid JS
$safe = HtmlSpecialChars($json); # this allows it to be used in an HTML attribute
echo "<img src=someimage.gif onclick=\"foo($safe)\">";
You can see a demo here: http://codepad.org/TK45YErZ
If I'm not interpreting badly you may do this:
// This is a PHP block of code
// $someText is text retrieved from the database
echo "<img src=someimage.gif onclick=\"foo('{".trim( preg_replace( '/\s+/', ' ',$someText ) )."}')\">";
You'll save yourself a lot of headaches by pulling the JavaScript out of the HTML:
<img id="myImage" src="someimage.gif"/>
<script type="text/javascript">
var str = <?php echo json_encode($json); ?>;
document.getElementById('myImage').addEventListener(
'click',
function() {
foo(str);
}
);
</script>
Or something similer...
Only json_encode() is enough to escape the new line
echo "<img src=someimage.gif onclick=\"foo(".json_encode($newData).")\">";
i have problem with between php and jQuery/Javascript...It wont show up or can't work.
My Code:
if($bottom_1_banner == "true"){
//$data_AD .= '$(\'.ban_bottom\').html(\''.htmlentities($bottom_banner).'\').text();';
$data_AD .= '$(\'.ban_bottom\').html("'.htmlspecialchars($bottom_banner).'").text();';
}
Error Log: (Chrome/Safari)
<script type="text/javascript">
$(document).ready(function() {
$('.ban_bottom').html("<!-- xxxxxxx -->
******index.php:11 Uncaught SyntaxError: Unexpected token ILLEGAL******
<script type="text/javascript">
xxxxxxx_bid = "xxxxxxxxxxx";
</script>
<script type="text/javascript" src="http://xxx.xxxxxx.com/k.js"></script>
<!-- xxxxxxxx -->").text(); });
</script>
OR
Edited: Converted Image to Text.
I had the same problem with the new line in JavaScript. If you are getting the value from MySql you can try this:
$php_string = str_replace('<br />','<br />\\',nl2br($php_string));
First replace the line-break with an html <br/> tag and then add the \ after the generated <br/> tag; So the JS line always ends with a \, that indicates a correct new line in the JavaScript code.
Based by your code above, one thing for sure, you need to define $data_AD variable before using .= or just use = without .
Maybe do
$data_AD .= '$(\'.ban_bottom\').html("'.$bottom_banner.'").text();';
...
<?php echo str_replace('\n', '\\n', $data_AD); ?>
to remove the line breaks?
Get rid of the new lines in the HTML. Javascript doesn't understand strings on multiple lines. You can alternatively replace the \n with \ \n:
This does not work:
var a = "This is a
string for me";
This works
var a = "This is a \
string for me";
or
var a = "This is a string for me";
This line of code works flawless here.
I'd guess its an file encoding issue with the .php-file. Check for bad characters.
I can't figure out how to get the same result from my Javascript as I do from my PHP. In particular, Javascript always leaves out the backslashes. Please ignore the random forward and backslashes; I put them there so that I can cover my basis on a windows system or any other system. Output:
Input String: "/root\wp-cont ent\#*%'i#$#%$&^(###''mage6.jpg:"
/root\wp-content\image6.jpg (PHP Output)
/rootwp-contentimage6.jpg (Javascript Output)
I would appreciate any help!
PHP:
<?php
$path ="/root\wp-cont ent\#*%'i#$#%$&^(###''mage6.jpg:";
$path = preg_replace("/[^a-zA-Z0-9\\\\\/\.-]/", "", $path);
echo $path;
?>
Javascript:
<script type="text/javascript">
var path = "/root\wp-cont ent\#*%'i#$#%$&^(###''mage6.jpg:"; //exact same string as PHP
var regx = /[^a-zA-Z0-9\.\/-]/g;
path = path.replace(regx,"");
document.write("<br>"+path);
</script>
Your problem is that you're not escaping the backslashes in your JS string, which you should always do (even in PHP) if you mean a backslash.
Example:
var path = "/root\wp-cont ent\#*%'i#$#%$&^(###''mage6.jpg:";
alert(path);
path = "/root\\wp-cont ent\\#*%'i#$#%$&^(###''mage6.jpg:";
alert(path);
Yup, Qtax is correct, then you can use this:
var regx = /[^a-zA-Z0-9\.\/-\\]/g;
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>