【问题标题】:Format text to left向左格式化文本
【发布时间】:2011-03-12 19:24:35
【问题描述】:

我正在创建一个格式工具,用于从文章中剥离内容以供打印。演示可以看到here。完整的来源是可用的here

现在工具条格式化并且还可以使用nl2br保留段落我想做的是能够将内容向左移动,并且如果内容之间有中断,则只有一个段落。

例如:

这个


第一
段落

第二段

变成:

这是第一段

第二段

我尝试使用正则表达式检查末尾是否有两个空格,但这不起作用。这是一些示例代码: HTML:

<form method="post" action="">
    <textarea cols="68" rows="21" name="textinput"></textarea><br/>
    <input type="checkbox" name="keep_paragraphs" value="true" checked /> Keep Paragraphs<br/>
    <input type="checkbox" name="shift_left" value="true" /> Remove whitespace after line unless it ends in two spaces<br/>
    <input type="submit" value="Submit" />
    </form>

PHP:

$text= $_POST['textinput'];
        $p= $_POST['keep_paragraphs'];
        $lb= $_POST['shift_left'];
        if(get_magic_quotes_gpc()){
        $text = stripslashes($text);
        // strip off the slashes if they are magically added.
        }
        $text = htmlentities($text);
        //if we should keep formatting
        if($p=="true"){
            $text =nl2br($text);
        }
        if($lb=="true"){
            $text = preg_replace('/\s+/', ' ', trim($text));
        }
echo $text;

这方面的任何帮助都会很棒

编辑:包含示例

POST 文本框 = "嗨,简

今天过得怎么样

希望一切都好”;

大多数文本将来自电子邮件和其他来源,基本上需要超级性别。

【问题讨论】:

    标签: php regex preg-replace trim nl2br


    【解决方案1】:

    您需要的正则表达式是,

    /(?&lt;!\r\n)\r\n(?=\w)/

    用空格替换它。

    更新

    一个小的修正,

    
    $text ="This
    is
    a
    paragraph  
    
    Second Paragraph";
    
    $lb = "true";
    if($lb=="true"){
                $text2 = preg_replace('/(?<!\r\n)\r\n(?=\w)/', ' ', trim($text));
    
            }
    
    echo $text2;
    

    【讨论】:

    • 它似乎可以在键盘上工作,但不能在我的实际软件上工作是 htmlentitiesstripslashesnl2br 打算对格式化做些什么并破坏 preg_replace?
    • 试试/(?&lt;!\r*\n)\r*\n(?=\S)/——让它更通用,如果你可以在htmlentitiesnl2br之后粘贴真实的输入,我可以微调正则表达式。
    • 这会产生一个 php 错误:Warning: preg_replace(): Compilation failed: lookbehind assertion is not fixed length at offset 9 codepad.org/yVC1rJkf P.S.谢谢!
    • 请提供您正在处理的真实数据样本。
    • 文本来自文本框。或多或少的人会从电子邮件等复制。我在上面添加了一个示例。我的主机看不到/r/n 也可能是 php 问题
    【解决方案2】:

    你可以这样写

    $text = preg_replace('@\n([a-z])@Us', ' \1', trim($text));
    

    【讨论】:

    • 如果我没记错的话就是在codepad.org/htGXDmuC文本前添加2个空格
    • 使用这个$text = preg_replace('@\s*?\n*\s*([a-z])@Us', ' \1', trim($text));
    • 感谢@azat,这非常接近,它只是在每个字母之间添加一个空格。 codepad.org/ylikDz0e 如果我删除'\1' 中的空格,则第二段有效,但第一段没有空格。感谢您的帮助。
    猜你喜欢
    • 2021-06-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-09-12
    相关资源
    最近更新 更多