admin管理员组

文章数量:1336632

I am developing a script which get all the content from a webpage using file_get_contents() then it removes all the HTML, JavaScript and CSS formatting and stores it in a variable.

Then I assign that PHP variable to JavaScript variable. Now my problem is that the text (which I have assigned to JavaScript var) contains many newlines which gives me a JavaScript error on running my program.

Simple str_replace("\n", "", $text); didn't work for me. I have also tried ltrim, trim, rtrim.

I am developing a script which get all the content from a webpage using file_get_contents() then it removes all the HTML, JavaScript and CSS formatting and stores it in a variable.

Then I assign that PHP variable to JavaScript variable. Now my problem is that the text (which I have assigned to JavaScript var) contains many newlines which gives me a JavaScript error on running my program.

Simple str_replace("\n", "", $text); didn't work for me. I have also tried ltrim, trim, rtrim.

Share Improve this question edited Aug 19, 2013 at 15:11 jeromej 11.7k3 gold badges45 silver badges65 bronze badges asked Jan 3, 2011 at 14:55 AyushAyush 631 silver badge5 bronze badges
Add a ment  | 

6 Answers 6

Reset to default 4

You are assigning a string to a JavaScript variable, you could use json_encode.

Like this:

<script type="text/javascript">
var g_text = <?php echo json_encode($text); ?>;
</script>

Note: You can also pass arrays and numbers to JavaScript this way.

You only need one call:

$string = str_replace(array("\r", "\n"), '', $string);

or

$string = strtr($string, "\r\n", '');

There's no need for multiple calls, or for having multiple binations... Yet it still takes care of the 3 possible line ending sequences (Windows \r\n, Linux \n, Mac \r)...

Have you tried str_replace("\r\n", "", $text); ?

Try this code. It replaces all possible newline in all OS.

str_replace("\r\n", "", $text); // Replace CR+LF
str_replace("\r", "", $text);   // Replace CR
str_replace("\n", "", $text);   // Replace LF

I suppose the stored string contains html, right? If you want you can use nl2br to convert the \n to the BR tag.

FYI: Please remember to always use double quotes when searching/replacing newline characters. If you use single quotes like:

print str_replace(array('\n', '\r\n', '\r'), '', $strBorked);

It will never work! You must use:

print str_replace(array("\n", "\r\n", "\r"), '', $strBorked);

This is because PHP does not interpret inside of single quotes, and \n is a character php only translates to a literal newline when inside of double quotes. This of course applies to all control characters.

本文标签: javascriptReplace new linePHPStack Overflow