How to replace new line with %0D%0A with PHP - javascript

I have a JavaScript code that can replace new lines with %0D%0A
I need the same code in PHP.
This is how my JavaScript code looks like:
text = text.replace(/\n\r?/g, '%0D%0A');
I tried with PHP but I am getting only one line without newlines.

You don't need regular expressions for that. Simple string replacement will be enough.
Use str_replace function:
$test = 'Some very long text with multiple lines...';
$newText = str_replace(PHP_EOL, '%0D%0A', $text);
New line character differs in various systems. It's not a good idea to hard-code \n\r. Better solution is to use PHP_EOL constant.

a literal translation of your java code into php could use preg_replace
http://www.php.net/preg_replace
<?php
$text = "some text";
$text = preg_replace("\r\n","%0D%0A",$text);
?>

Related

Cannot echo strings with "" , '' and /n from PHP to JavaScript

I tried to show a description from the YouTube API to p element but it's not working. I think the problem is with the quotes, single quote and new line; ie. "" , '' and \n.
This is the description text:
Another contestant attempts to overcome 'Head Case'! Will Daniel be able to "master" his fear of the unknown and be able to carry on singing?\n\nSubscribe for more awesome clips!\n\nSubscribe now!
$description = $vid["items"][0]["snippet"]["description"];
echo "<script>$('.pClass:nth-of-type(4)').text($description);</script>";
Note that it's working like this: $('.pClass:nth-of-type(4)').text('test');, but it's not working when read from the API.
You're outputting data to JavaScript, so you need to escape it in a way that will be safe for JavaScript to consume. Since JSON is a subset of JavaScript, you can use json_encode() for this purpose.
You should also avoid outputting JS in a double-quoted string; you can have problems with JS values being interpreted as PHP variables.
<?php
$description = json_encode($vid["items"][0]["snippet"]["description"]);
?>
<script>
$('.pClass:nth-of-type(4)').text(<?=$description?>);
</script>

json_encode() gives special charactors like '\n'..how can i replace them in PHP?

I encoded an array using json_encode() function and it gave me a string like this..
"[{"details":"power - 2000w \nac-220-240v \/ 50-60hz\n369 degree cordless base\n","model_id":"MC-EK3428 \/ MC-EK3328"}]"
as you can see it contains special characters like "\n"..I want these special characters to be replaced with "" because in javascript I am using the JSON.parse(); function to convert this string to an object..
but it gives me an error
syntaxerror : missing ) after argument list
I think this is because of the special characters in the string..how can I escape these?
Edit
php :
$view->jsonencoded_array = json_encode($array);
javascript :
var products = JSON.parse('<?php echo $jsonencoded_array; ?>');//this line gives me the error
update :
found out that the error is given in this :
'<?php echo $jsonencoded_array; ?>'
The problem here is that \n (and various other combinations) have special meaning inside a JavaScript string, and you are dumping your JSON into a JavaScript string without doing any conversion of those characters.
Since JSON is heavily inspired by JavaScript literal syntax, you can use json_encode to convert a PHP string into a JavaScript string.
There are some gotchas, the main one being that </script> can appear in a JSON text without causing any problems, but having that in the middle of your JavaScript <script> element is going to cause the HTML parser to cut off your JavaScript in the middle of the string … but PHP's default encoding rules will generate <\/script> which solves that problem.
So:
<?php
$json_array = json_encode($array);
$javascript_string = $json_encode($json_array);
?>
var products = JSON.parse(<?php echo $javascript_string; ?>);
That said. A JSON array is also a JavaScript array, so you can skip that step entirely.
<?php
$json_array = json_encode($array);
?>
var products = <?php echo $json_array; ?>;
There must something that you are missing or there is some other reason for your issue while parsing in JavaScript; because json_encode handles \n and other special characters such " \ etc. very well and escape them properly without any explicit work.
I would suggest you to check the JSON produced and you are supplying to JavaScript and see if there is something missing in between.
Note: You can do a str_replace but it is not advised. Better stick to json_encodesince its s standard function and it works well.
Edit:
You should be echoing $view->jsonencoded_array not just $jsonencoded_array, no need to parse already JSON object.
php :
$view->jsonencoded_array = json_encode($array);
javascript :
var products = <?php echo $view->jsonencoded_array; ?>;
json_encode() twice helped me to solve this issue..
$view->jsonencoded = json_encode(json_encode($array));

Forward slash is changing to backward slash and forward slash

I have converted normal text into json with json_encode(data), but the problem is
normally written images/data.png is converted to images\/data.png i have to remove this extra backslash. How is it possible
In a JSON string, / and \/ are equivalent. You should not need to enforce the former syntax.
If you think you need to change them then you are either:
Designing too much for text editors instead of JSON parsers or
Being overly concerned with individual bytes
Escaping / provides a defence against premature script termination when you have code like this:
<?php
$data = Array( "</script>" );
?>
<script>
var data = <?php echo json_encode($data); ?>;
</script>
That said, if you really want to remove it, PHP provides an option for it:
json_encode($data, JSON_UNESCAPED_SLASHES);

Javascript Regular Expression Code to PHP Regular Expressions ?

I have following java script regular expression which i need to convert to similar php converter.
text = text.replace(/R/g, "ූ");
Can someone help me to convert this into PHP ?
It's very similar:
$text = preg_replace('/R/', "ූ", $text);
Have look at the preg_replace documentation.
its regex counterpart in php will be :
preg_replace( '/R/', 'your replacement string', $text );
$text = the value of 'text' in your javascript code.
However, for simple text replace, regular expressions are expensive. If your problem can't be solved using simple string functions then only use regex.

jquery unterminated string literal when loading dynamic content

$str is loading dynamic content from admin panel (tinymce) in following format
$str = 'First Line
Second Line
Third Line';
Now when i try to access this variable then it gives me unterminated string literal
<script type="text/javascript">
$(document).ready(function() {
var a = '<?php echo $str;?>';
$('#abc').html(a);
});
</script>
<div id="abc"></div>
when i convert string to $str = 'First line Second line Third line'; then it does not give error but my string is in above way.
When dumping a PHP variable into JavaScript, ALWAYS use json_encode. Like this:
var a = <?php echo json_encode($str); ?>;
Note no quotes around the PHP code, this is important! PHP will add the quotes for you and escape everything correctly.
It's the line breaks, they're not valid inside a JavaScript string literal. If you want multiple lines in a JavaScript string, use a backslash (\):
var testString = 'This is \
a test';
Even then, multiple whitespace (including linebreaks) will be removed when it's set as the content of an HTML element.
That said, I don't see why you're using the JavaScript to do this at all, you could simply do:
<div id="jaspreet"><?php echo $str;?></div>

Categories

Resources