phpregexucfirst

First character upper case and ignore few special characters in php


I am trying to dispaly upper case text to just the first character to be upper case in a phrase. If there are any special characters they have to be ignored.

for example:

SECTION 1: IDENTIFICATION OF THE SUBSTANCE/PREPARATION AND OF THE COMPANY/UNDERTAKING

the above is my text and I want the above text to display like

Section 1: Identification of the substance/preparation and of the company/undertaking

as of now I tried echo ucfirst(strtolower($word));

which outputs

Section 1: identification of the substance/preparation and of the company/undertaking

How can I achieve this? Thank you


Solution

  • You can split using : surrounded by optional spaced and call ucfirst on each split item and then join them together:

    $out="";
    
    foreach (preg_split('/(\h*[:.]\h*)/', strtolower($str), 0, PREG_SPLIT_DELIM_CAPTURE) as $s)
       $out .= ucfirst($s)
    
    echo "$out\n";
    
    //=> Section 1: Identification of the substance/preparation and of the company/undertaking
    

    \h*[:.]\h* splits on : or . with optional spaced on either side. You may add more characters here in character class that you want to split on.