Daniele
Daniele

Reputation: 129

PHP - Capitalize the first letter after a dot or after a dot and a space

I would like to capitalize the first letter after a dot or after a dot and a space.

$string="I am a string with several periods.period #1. period #2.";

This should be the final string:

I am a string with several periods.Period #1. Period #2.

I have already searched for a solution on stackoverflow but the solution that i found was only for capitalize the initial letter after just a dot and not for a dot and a space.

Upvotes: 3

Views: 2791

Answers (4)

Sherif Salah
Sherif Salah

Reputation: 2153

I created this simple function and it works like a charm

and you can add delimiters as you like.

function capitalize_after_delimiters($string='', $delimiters = array())
{
    foreach ($delimiters as $delimiter)
    {
        $temp = explode($delimiter, $string);
        array_walk($temp, function (&$value) { $value = ucfirst($value); });
        $string = implode($temp, $delimiter);
    }
    return $string;
}

$string ="I am a string with several periods.period #1. period #2.";

$result = capitalize_after_delimiters($string, array('.', '. '));

var_dump($result);

result: string(56) "I am a string with several periods.Period #1. Period #2."

result

Upvotes: 1

erickb
erickb

Reputation: 6299

If regex is not an option, something like this might work:

$str = "I am a string with several periods.period #1. period #2.";
$strings = explode('.', $str);
$titleCased = [];

foreach($strings as $s){
    $titleCased[] = ucfirst(trim($s));
}
echo join(".", $titleCased);

Although, this has the added effect of removing whitespace.

https://3v4l.org/fWGUW

Upvotes: 0

Toto
Toto

Reputation: 91518

Preg_replace_callback is your friend:

$string="I am a string with several periods.period #1. period #2.";
$string = preg_replace_callback('/\.\s*\K\w/', 
    function($m) {
        return strtoupper($m[0]);
    },
    $string);
echo $string;    

Output:

I am a string with several periods.Period #1. Period #2.

Upvotes: 3

Andreas
Andreas

Reputation: 23968

Use regex to match the dot \., optional space \s* and a letter \w.
Then loop the matches array and do a str_replace.

$str="I am a string with several periods.period #1. period #2.";
preg_match_all("/\.\s*\w/", $str, $matches);

foreach($matches[0] as $match){
    $str = str_replace($match, strtoupper($match), $str);
}
echo $str;
//I am a string with several periods.Period #1. Period #2.

https://3v4l.org/LevU5

To make it slightly more optimized you could add an array_unique before looping since str_replace replaces all equal substrings.

$matches[0] = array_unique($matches[0]);

https://3v4l.org/mIiX8

Upvotes: 1

Related Questions