【问题标题】:add new extra line after all paragraph在所有段落之后添加新的额外行
【发布时间】:2013-08-30 07:43:47
【问题描述】:

我正在从 url 获取内容并将它们存储在数据库中。 在此之前,我将所有内容转换为纯文本。 为此我做了这个。

我想在所有段落之后添加新的额外行。

我试过了,结果不是很清楚..

$string = "<p>As a result, his move to Microsoft has raised many questions about the Redmond-based company's plans in the PC gaming space.</p><p>With the Xbox One launch looming, Microsoft has greatly de-emphasized PC gaming of late. </p><p>Holtman's hiring could signal a renewed emphasis on the computer, though.</p>

在我看来,一个来自 Valve 的人似乎在游戏领域没有同行,相对于真正强大的 B2C [企业对消费者] 关系可能表明这一点的重要性正在上升Arcadia Investment Corp. 董事总经理 John Taylor 说。

" ;
$search = array('@<script[^>]*?>.*?</script>@si', // Strip out javascript    
            '@<[\/\!]*?[^<>]*?>@si', // Strip out HTML tags    
            '@<style[^>]*?>.*?</style>@siU', // Strip style tags properly    
            '@<![\s\S]*?--[ \t\n\r]*>@' // Strip multi-line comments including CDATA
        );

// remove excess whitespace        
// looks for a one or more spaces and replaces them all with a single space.        
$string = preg_replace($search, '', $string);        
$string = preg_replace('/ +/', ' ', $string);        
// check for instances of more than two line breaks in a row    
// and then change them to a total of two line breaks          
$string = preg_replace('/(?:(?:\r\n|\r|\n)\s*){2}/s', "\r\n\r\n", $string);
file_put_contents('testing.txt', $string );

【问题讨论】:

  • 你能给我们一个你正在寻找的样本输入和输出吗?
  • @C.Malet 我添加了示例测试。谢谢..

标签: php string string-parsing plaintext


【解决方案1】:

你没有给出想要的输出,但我认为你想要类似的东西:

<p>Text</p>\r\n
<p>Another text</p>\r\n

不要使用繁重的 REG EXP,只需在 &lt;/p&gt; 上爆炸并添加额外的行:

$array = explode ('</p>', $string);
new_string = '';
$temp = count ($array);
foreach ($array as $key => $paragraph)
{
    if ($key !== $temp - 1);
        $new_string .= $paragraph . "</p>\r\n";
    else
        $new_string .= $paragraph;
}

$new_string 变量应该是您正在寻找的,如果我是对的,请告诉我。 它在 every &lt;/p&gt;

之后添加 \r\n

【讨论】:

  • 已编辑答案,代码在以下输入中未按预期工作:&lt;p&gt;Text&lt;/p&gt;&lt;p&gt;Another text&lt;/p&gt;Something else。 'Something else' 最后多了一个不需要的&lt;/p&gt;。
【解决方案2】:

您用来添加额外换行符的正则表达式有错误 - 正确的版本是:

$string = preg_replace('/(?:(?:\r\n|\r|\n)\s*){1,}/s', "\r\n\r\n", $string);

区别如下:{2}(就像在您的代码中一样)确保您仅在已有两个换行符时添加一个额外的换行符。 (它需要 两个 匹配表达式 (?:(?:\r\n|\r|\n)\s*)。)

将 {2} 更改为 {1,} 可确保您添加一个独立于现有换行符数量的额外换行符。

【讨论】:

  • 感谢 gr8 它非常简单的方法.. 我的想法在哪里.. :P :)
猜你喜欢
  • 2015-10-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-10-15
  • 2013-04-30
  • 2013-08-11
  • 2016-11-05
相关资源
最近更新 更多