PHP str_replace of input from javascript - php

I am running some ajax that sends escaped text from the client to a php page running on the server. The text has some carriage returns in it. When I echo these out using php they show up in the text as \n.
However when I try to replace \n using str_replace, the function does not find them.
This has been driving me crazy.
By contrast, I manually created a variable in the same php file with a bunch of \n s in it and in that case the same str_replace code replaced them fine.
Could there be some invisible characters or something throwing it off?
Thanks for any suggestions.
Following replace (all in PHP) works fine
$var = "some text\nsomemore text\nsome more text\nsome more";
echo $var; //displays above text
$strComma = str_replace("\n",",",$var);
echo "strComma".$strComma; \\all of the \n instances are replaced by comma
Following replace does not work
javascript (abbreviated)
var text = document.getElementById(textbox).value; //grabs text from client html
var text2 = escape(text); //escape needed to handle special characters in text
//send to php page
xmlhttp.open("GET","storetext.php?text="+text2,true);
xmlhttp.send();
PHP
$var = $_REQUEST['text'];
echo $var; //displays \n as above. So far so good.
$strComma = str_replace("\n",",",$var);
echo "strComma".$strComma; \\ replacement does not take place

This should work:
$strComma = str_replace("\\n",",",$var);
Two backslashes and then the n character. Like escaping the escape sequence.

When I try with str_replace nothing changes, but using preg_replace it does like this
$strComma = preg_replace("/\n/",",",$var);
ok, html
<html>
<head>
<script src="../../js/jquery_1_8_min.js" type="text/javascript"></script>
</head>
<body>
<script>
text = "some text\nsomemore text\nsome more text\nsome more";
text2 = escape(text)
$.post('lixo.php?'+Math.random(),{text:text2}, function(data) {
alert(data);
});
</script>
</body>
</html>
php
<?php
$var = $_POST["text"];
echo $var; //displays above text
$strComma = preg_replace("/%0A/",",",$var);
$strComma = preg_replace("/%20/",",",$var);
echo "<br>strComma = ".$strComma;
?>
when you escape your text \n becames %0A and white space becames %20
better php
<?php
$var = $_POST["text"];
echo $var."<br>";
$patterns = array();
$patterns[0] = "/%0A/";
$patterns[1] = "/%20/";
$replacements = array();
$replacements[0] = ",";
$replacements[1] = " ";
$strComma = preg_replace($patterns, $replacements,$var);
echo "<br>strComma = ".$strComma;
?>

Related

I want to echo php text but not between ()

I want to echo php text but not between (). Some thing like this =
<?php
$text = "Barry(male)";
echo $text;
?>
output =
Barry
How can i do this?
You can use preg_replace to substitute whatever is between parenthes (and the parentheses themselves) with an empty string. Like this:
<?php
$text = "Barry(male)";
echo preg_replace('#\(.*\)#', '', $text);
?>
Please note: since you didn't specify your string format, I'm assuming that the parenthesized text appears just once in the string and that there aren't nested parenthes. Otherwise, this doesn't work as expected.
Something like:
$text = "Barry(male)";
$split = explode("(", $text);
echo $split[0];
// "Barry"

How to add new line in php echo

The text of story content in my database is:
I want to add\r\nnew line
(no quote)
When I use:
echo nl2br($story->getStoryContent());
to replace the \r\n with br, it doesn't work. The browser still display \r\n. When I view source, the \r\n is still there and br is nowhere to be found also. This is weird because when I test the function nl2br with simple code like:
echo nl2br("Welcome\r\nThis is my HTML document");
it does work. Would you please tell me why it didn't work? Thank you so much.
The following snippet uses a technique that you may like better, as follows:
<?php
$example = "\n\rSome Kind\r of \nText\n\n";
$replace = array("\r\n", "\n\r", "\r", "\n");
$subs = array("","","","");
$text = str_replace($replace, $subs, $example );
var_dump($text); // "Some Kind of Text"
Live demo here
I doubt that you need "\n\r" but I left it in just in case you feel it is really necessary.
This works by having an array of line termination strings to be replaced with an empty string in each case.
I found the answer is pretty simple. I simply use
$text = $this->storyContent;
$text = str_replace("\\r\\n","<br>",$text);
$text = str_replace("\\n\\r","<br>",$text);
$text = str_replace("\\r","<br>",$text);
$text = str_replace("\\n","<br>",$text);

Handling strings with linebreaks in vars

I'm trying to get it once again.
I got a JS var which looks like this:
var test;
Now I write some JS with PHP:
<?php
$phpvar = "a text with
a linebreak";
echo "<script type='text/javascript'>
var test;
test = '" . $phpvar . "';
</script>";
?>
Now, if I run it, it outputs the source as follows:
<script type='text/javascript'>
var test;
test = 'a text with
a linebreak';
</script>
This gives me a JS exception:
ERROR: unterminated string literal
Somehow, JS seems not to recognize that there is a string on more than one line.
How can I realize this if, in the end, the string must have its linebreak again? (So, if all execution finishes, I must have the string including all linebreaks)
Thank you for your help ;)
Try this, if you use a \ at the end of a Javascript line, you can use multiple lines within a string.
<?php
$phpvar = "a text with
a linebreak";
echo "<script type='text/javascript'>
var test;
test = '" . str_replace("\n", "\\\n",$phpvar) . "';
</script>";
?>
escaping in php:
js: php:
<linebreak> \n
\ \\
\n \\n
If you want this:
var test = "te\
st";
console.log(test) > "test"
in this case you need to use a \ and <linebreak> (in js), so you need to replace the \n to \\ plus \n (in php)
<?php
$phpvar = "a text with
a linebreak";
echo "<script type='text/javascript'>
var test;
test = '" . str_replace("\n", "\\\n",$phpvar) . "';
</script>";
?>
this keep the linebreaks as a php but not in the javasccript
But if you want to keep the linebreaks in javascript like this:
console.log(test) > "te
st"
You need to add a \n as an escaped string, not as a linebreak character.
So the code will look like this
var test = "te\n\
st"
console.log(test) > "te
st"
In this case you need a \n and a \ and a <linebeak> (in js), so you need to replace the the \n to a \\n plus \\ plus \n
<?php
$phpvar = "a text with
a linebreak";
echo "<script type='text/javascript'>
var test;
test = '" . str_replace("\n", "\\n\\\n",$phpvar) . "';
</script>";
?>
this keeps the linebreaks in php, and also add linebreaks into the javascript

Processing each line of a textarea form in a script

I've learned it's possible to trim a string from a textarea and put break tags after it, so each sentence written at a new line in the textbox will also be written at a new line in the PHP file.
This is the snippet:
<html>
<body>
<?php
$text = trim($_POST['textarea']);
$text = nl2br($text);
echo $text;
?>
</body>
</html>
The thing is that my true intentions are:
Use the contents of each line in the textbox for a certain script
Print the contents of each line with the results from the script added all separated by lines.
<?php
$text = trim($_POST['textarea']);
$text = explode ("\n", $text);
foreach ($text as $line) {
echo myFunction($line);
echo "< hr />";
}
?>
The PHP function explode lets you take a string and blow it up into smaller pieces. Store this array for use in other scripts
$str_arr = explode("\n", $_POST['textarea']);
//$str_arr can be used for other script

How to handle newlines in Javascript? (from PHP)

I have code like this:
<?php
echo '<script type="text/javascript">';
echo 'var out="'.$txt.'";';
echo '</script>';
?>
Where $txt is a PHP variable that can contain newlines like this:
line1
line2 hello world
Which would end up like this:
var out="line1
line2 hello world";
Which will cause a Javascript error, of course.
What is the best way to handle this? The out variable will be used in a HTML textarea, so I don't think it can be parsed into <br>
$txt = str_replace( array( "\n", "\r" ), array( "\\n", "\\r" ), $txt );
should replace newlines. Don't do it this way.
This is a naïve implementation of string escaping for JavaScript. As you're actually trying to format a string for use in JavaScript, a much better solution would be to use json_encode:
$txt = json_encode($txt);
echo "<script>var out={$txt};</script>";
json_encode will correctly escape special characters in strings, such as quotes, tabs, form feeds, and other special unicode characters. It will also perform all the correct escaping for converting objects, arrays, numbers, and booleans.
you can add a \ at the end of a line to create a multi line String
var out="line1 \
line2 hello world";
Most of these don't work for me.
Normally, I'd use json_encode like
<?php
$MyVar = json_encode($MyVar);
?>
<javascript language='javascript'>
MyVar = <?php echo $MyVar; ?>
But for a quick fix you can just break a line like this:
Pay attention to the double quotes.
<?php
$MyVar = "line one here
then line two here
finally line five here";
//** OR
$MyVar = $MyVarA .
"
"
. $MyVarB;
?>
<HTML>
<HEAD>
<javascript language='javascript'>
Myvar = "<?php echo $MyVar; ?>";
. . .
You can use str_replace to convert line breaks into a different character (in this case, perhaps a space, but it depends how you want the output to show up)
$out = str_replace("\n", '\n', $in);
$content = str_replace( "\\n", "\\\\\\n", $content );
Result:
var a = "Hello \
World"
I tried this and it worked well.
<?php
echo '<script type="text/javascript">';
$txt = "line1 \\n line2 hello world";
echo 'var out="'.$txt.'";';
echo '</script>';
?>
I am using PHP 5.3

Categories