Home > Article > Backend Development > php format text into Js usable format
This article shares with you the use of PHP to format multi-line text into JS usable format. The idea is very simple. It is recommended to everyone here for reference by friends in need.
There are many scenarios for storing and writing templates in js, such as HTML code templates for pop-up boxes, etc. JS does not support long text writing with line breaks, and must be added up line by line, such as:
The code is as follows:
var content = '<p>row 1</p>' + '<p>row 2</p>';
but cannot be written as:
The code is as follows:
var content = '<p> row 1</p> <p>row2 </p> ';
So I processed a small piece of php code to simplify the manual typing operation.
tojs.php
<!DOCTYPE HTML> <head> <meta http-equiv="Content-Type" content="text/html;charset=UTF-8"> <title>Str To Js String</title> <style type="text/css"> .content-box { border: 1px #f0f0f0 slid; border-left: 4px #e0e0e0 solid; padding: 5px 5px 5px 10px; } </style> </head> <body> <h1>输入格式化的文本:</h1> <?php $jsContent = ''; if(isset($_POST['content']) && $_POST['content']) { $content = strtr(htmlspecialchars($_POST['content']), array("\r\n" => "\n")); $rows = explode("\n", $content); foreach($rows as $row) { $jsContent .= '+ \'' . $row . "'<br/>"; } $jsContent{0} = ' '; } ?> <form action="#" method="post"> <textarea name="content" style="width: 99%;height: 300px; "></textarea> <p><input type="submit" value="提交" /></p> </form> <h2>格式化后的结果:</h2> <p class="content-box"> <?php echo $jsContent;?> </p> </body> </html>
Summary: The above is the entire content of this article, I hope it will be helpful to everyone's study.
Related recommendations:
How to convert numbers into Chinese characters in php
php function for uploading image files Detailed explanation
php image upload and the use of javascript plug-in
The above is the detailed content of php format text into Js usable format. For more information, please follow other related articles on the PHP Chinese website!