Search code examples
phpstringstring-parsingplaintext

add new extra line after all paragraph


I am fetching content from a url and storing them in database. Before this i am converting all content in plain text. for this i did this.

I wants to add new extra line after all paragraph.

I have tried but not so clear result..

$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>

It seems like a guy who comes from Valve who has no peer, in my mind, in the gaming space relative to really strong B-to-C [business to consumer] relations could indicate a ramp up in the importance of that space, says John Taylor, managing director at Arcadia Investment Corp.

" ;

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

Solution

  • You didn't give the wanted output, but I think you want something like :

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

    Instead of using heavy REG EXP, just explode on </p> and add your extra lines :

    $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;
    }
    

    The $new_string var should be what you're looking for, tell me if I'm right. It adds \r\n after every </p>