Pregunta

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 );
¿Fue útil?

Solución

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>

Otros consejos

The regular expression you use to add the extra newline has an error - the correct version is:

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

The difference is the following: {2} (as it is in your code) makes sure that you only add an additional newline if there already are two newlines. (It requires two matches for the expression (?:(?:\r\n|\r|\n)\s*).)

Changing {2} to {1,} makes sure that you add an extra newline independently from the number of existing newlines.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top