0

我正在从 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 [企业对消费者] 关系而言,在游戏领域没有同行,这可能表明该领域的重要性正在上升,说阿卡迪亚投资公司董事总经理约翰·泰勒

";

$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 );
4

2 回答 2

1

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

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

而不是使用繁重的 REG EXP,只需爆炸</p>并添加额外的行:

$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 var 应该是您要查找的内容,请告诉我我是否正确。它在每个之后添加 \r\n </p>

于 2013-08-27T14:19:40.163 回答
1

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

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

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

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

于 2013-08-27T14:24:08.087 回答