Search code examples
phpregexpreg-replacepreg-replace-callback

PHP Replace the very first lower cased char of every line by upper case


I've tried using the below

$string= 'hello world<br>this is newline<br><br>another line';
echo $string.'<hr><br>';
echo preg_replace_callback('/^[a-zA-Z0-9]/m', function($m) {
  return strtoupper($m[0]);
}, $string);

the output:

Hello world
this is newline

another line

i need to change the first letter of word "this" and "another" too. so the output become like this:

Hello world
This is newline

Another line

Thanks.


Solution

  • Here is how you can achieve what you want:

    $string= 'hello world<br>this is newline<br><br>another line<hr><br>';
    
    $parts = preg_split( "/<br>|<hr>/", $string ); // split string by either <br> or <hr>
    $parts = array_filter($parts); // clean array from empty values
    $parts = array_map('ucfirst',$parts); // array of lines with first letter capitalized
    
    echo $partString = implode("<br>",$parts);