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
.
6 Answers
Reset to default 4You 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
版权声明:本文标题:javascript - Replace new line | PHP - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742412252a2470019.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论