Question

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
Was it helpful?

Solution

This should work:

$strComma = str_replace("\\n",",",$var);

Two backslashes and then the n character. Like escaping the escape sequence.

OTHER TIPS

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;
?>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top