Search code examples
phpnl2br

How to get the first paragraph bold in the php?


I am entering text in the database in two paragraphs

first paragraph
second paragraph

I am storing them in my database and when I am displaying them on the frontend using nl2br it is getting displayed perfectly.

I want the my first paragraph to be bold and the second paragraph should be normal.

I tried using strpos to find the location of the <br> tag after nl2br to chop off the first paragraph but I am not succeeding.

the failed code is

echo strpos(nl2br($row['article']), "<br>");

but i am not getting the position of the <br> tag

I got the correct answer from eddie, he deleted it but i am updating the answer here

$str='first paragraph
      second paragraph';
foreach(explode("\n",) as $key => $val) { 
if($key == 0){
echo'<b>'; 
}     
echo $val;
echo'<br>';
if($key == 0){ 
echo '</b>';
}
}

Solution

  • Don’t use nl2br for the type of results you are looking for. Just split the string into an array using a regex rule with preg_split and then act on the first item in the array. Here is test code:

    // Set the test data.
    $test_data = <<<EOT
    first paragraph
    second paragraph
    EOT;
    
    // Split the test data into an array of lines.
    $line_array = preg_split('/(\r?\n){1,2}/', $test_data);
    
    // Roll through the line array & act on the first line.
    $final_text = '';
    foreach ($line_array as $line_key => $line_value) {
      if ($line_key == 0) {
        $line_value = "<b>" . $line_value . "</b>";
      }
      $final_text .= $line_value . "<br />\n";
    }
    
    // Dump the line array for debugging.
    echo '<pre>';
    print_r($line_array);
    echo '</pre>';
    
    // Echo the final text.
    echo '<pre>';
    echo htmlentities($final_text);
    echo '</pre>';
    
    die();
    

    The output from the dump of the line array would be this:

    Array
    (
        [0] => first paragraph
        [1] => second paragraph
    )
    

    And the test output using htmlentities to show what was done HTML-wise:

    <b>first paragraph</b><br />
    second paragraph<br />