I am trying to make "manner friendly" website. We use different declination dependent on gender and other factors. For example:
You did = robili
It did = robilo
She did = robila
Linguisticaly this is very simplified (and unlucky) example! I would like to change html text in php file where appropriate. For example
<? php
something
?>
html text of the page and somewhere is the word "robil"
<div>we tried to robil^i|o|a^</div>
<? php something ?>
Now I would like to replace all occurences of different tokens ^characters|characters|characters^ and replace them by one of their internal values according to "gender".
It is easy in javascript on the client side, but you will see all this weird "tokenizing" before javascript replace it.
Here I do not know the elegant solution.
Or do you have better idea?
Thanks for advice.
You can add these scripts before and after the HTML:
<?php
// start output buffering
ob_start();
?>
<html>
<body>
html text of the page and somewhere is the word "robil"
<div>we tried to robil^i|o|a^, but also vital^si|sa|ste^, borko^mal|mala|malo^ </div>
</body>
</html>
<?php
$use = 1; // indicate which declination to use (0,1 or 2)
// get buffered html
$html = ob_get_contents();
ob_end_clean();
// match anything between '^' than's not a control chr or '^', min 5 and max 20 chrs.
if (preg_match_all('/\^[^[:cntrl:]\^]{3,20}\^/',$html,$matches))
{
// replace all
foreach (array_unique($matches[0]) as $match)
{
$choices = explode('|',trim($match,'^'));
$html = str_replace($match,$choices[$use],$html);
}
}
echo $html;
This returns:
html text of the page and somewhere is the word "robil" we tried to
robilo, but also vitalsa, borkomala
Current Code:
<?php
include('conn.php');
$sql = mysql_query("select min(news_id) 'min' from news");
$res = mysql_fetch_array($sql);
$qry=mysql_query("select * from news order by date(post_date) desc,priority desc ");
while($row1=mysql_fetch_array($qry)) {
<p class='news_title'><a href='newsdetail.php?id=".urldecode($row1['news_heading'])."'>{$row1['news_heading']}</a></p>
}
?>
As I am passing the heading to the next page ...
The url in the next page is displaying like this
newsdetail.php?id=In%20front%20%20of%20the%20houses
I need to display like this:
newsdetail.php?id=In front of the houses
You can use urldecode to convert the URL string.
http://www.php.net/manual/en/function.urldecode.php
echo urldecode('newsdetail.php?id=In%20front%20%20of%20the%20houses');
will produce:
newsdetail.php?id=In front of the houses
You can't have spaces or special characters in the URL.
If you try to put them in, then the browser will put %20 for spaces.
for clean url please replace the space or special charcters with hypen(-)
function cleanURL($textURL) {
$URL = strtolower(preg_replace( array('/[^a-z0-9\- ]/i', '/[ \-]+/'), array('', '-'), $textURL));
return $URL;
}
while($row1=mysql_fetch_array($qry)) {
<p class='news_title'><a href='newsdetail.php?id=".cleanURL($row1['news_heading'])."'>{$row1['news_heading']}</a></p>
}
The output will be
newsdetail.php?id=In-front-of-the-houses
Think so this will help you
You can't have raw spaces in the URL. If you try to put them in, then the browser will error correct and escape them for you.
use this
$url = str_replace(' ', '-', strtolower($news_heading));
replace the space of this function
I have following script, which is not working. What to I do to add the link?
jno = "97856483";
dispTitle = "new book";
dispAuthor = "authorname";
document.getElementById('popups').innerHTML = '';
//Add link to add this book:
var url = encodeURIComponent(jno) + "&tt=" + encodeURIComponent(dispTitle) + "&at=" + encodeURIComponent(dispAuthor);
//document.writeln(url);
document.getElementById("addLink").innerHTML = "<a href='memaccountentry.php?isbn='+ url>Add book</a>" ; //This one just appends the word url.
//window.location.href = 'memaccountentry.php?isbn=' +jno +'&tt=' +dispTitle+'&at=' +dispAuthor; //I know this is working, but not a right way to do.
//I need to put a href link to go to the next page.
//ajax.open('GET', 'memaccountentry.php?isbn=' +jno +'&tt=' +dispTitle+'&at=' +dispAuthor', true);
You need to properly open and close your quotes.
Try that:
document.getElementById("addLink").innerHTML = "<a href='memaccountentry.php?isbn="+ url +"'>Add book</a>" ; //This one just appends the word url.
It looks like you didn't format your string correctly.
If this is not what you wanted, then you have me completely confused.
document.getElementById("addLink").innerHTML = "Add book";
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>