Home  >  Article  >  php教程  >  格式化多行文本到Js可用格式

格式化多行文本到Js可用格式

PHP中文网
PHP中文网Original
2016-05-26 08:19:061640browse

js里现在存写模板的场景好多,如:弹框类的html代码模板等,js不支持换行的长文本写法,必需要一行行的加起来,如:

var content = 'dc6dce4a544fdca2df29d5ac0ea9906brow 116b28748ea4df4d9c2150843fecfba68'
+ 'dc6dce4a544fdca2df29d5ac0ea9906brow 216b28748ea4df4d9c2150843fecfba68';
而不可以写成:
var content = 'dc6dce4a544fdca2df29d5ac0ea9906b row 116b28748ea4df4d9c2150843fecfba68
dc6dce4a544fdca2df29d5ac0ea9906brow2 16b28748ea4df4d9c2150843fecfba68 ';
于是小加工一php小段代码,简化手工打的操作

 [文件]     tojs.php 

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html lang="en">
    <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>

                               

                   

Statement:
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