-1

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.

chris85
  • 23,846
  • 7
  • 34
  • 51
dany
  • 177
  • 2
  • 13
  • 3
    `
    ` is not a new line in anything except a browser/application that is rendering HTML. You could try `/(^|
    )` or convert them to new lines. Also a `.` would probably be easier than a character class unless you only want to capitalize `a-z` (if that is case character class can be trimmed down to `[a-z]`).
    – chris85 Mar 03 '17 at 02:26
  • 2
    And why include `A-Z` and `0-9`? What are their uppercases? – AbraCadaver Mar 03 '17 at 02:43
  • 1
    You can change your regex to [`(?:^|<[bh]r>)\s*\K[a-z]`](https://www.regex101.com/r/Xxfnub/1) (see explanation on regex 101). Here is a [PHP demo at eval.in](https://eval.in/748045). – bobble bubble Mar 04 '17 at 17:26
  • @bobblebubble glad you came here – dany Mar 04 '17 at 17:32

1 Answers1

1

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);
Yolo
  • 1,569
  • 1
  • 11
  • 16