Home > Backend Development > PHP Tutorial > php format text into Js usable format

php format text into Js usable format

墨辰丷
Release: 2023-03-31 15:42:02
Original
1588 people have browsed it

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 = &#39;<p>row 1</p>&#39;
+ &#39;<p>row 2</p>&#39;;
Copy after login

but cannot be written as:

The code is as follows:

var content = &#39;<p> row 1</p>
<p>row2 </p> &#39;;
Copy after login

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 = &#39;&#39;;
if(isset($_POST[&#39;content&#39;]) && $_POST[&#39;content&#39;]) { 
  $content  = strtr(htmlspecialchars($_POST[&#39;content&#39;]), array("\r\n" => "\n"));
  $rows    = explode("\n", $content);
  foreach($rows as $row) {
    $jsContent .= &#39;+ \&#39;&#39; . $row . "&#39;<br/>";
  }
  $jsContent{0}  = &#39; &#39;;
} 
?>
    <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>
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template