0

I have got a function which is use to take a string and convert it to the desired form i.e. Sentence case.

function sentence_case($string) {
$sentences = preg_split('/([.?!]+)/', $string, -1, PREG_SPLIT_NO_EMPTY|PREG_SPLIT_DELIM_CAPTURE);
$new_string = '';
foreach ($sentences as $key => $sentence) {
    $new_string .= ($key & 1) == 0?
        ucfirst(strtolower(trim($sentence))) :
        $sentence.' ';
}

$new_string = clean_spaces($new_string);
$new_string = m_r_e_s($new_string);
return trim($new_string);
}

Now I want to modify this function for " i ", as whenever we have I in out sentence than it remain capital how can I add exception to particular words like..." i ", " i' " etc.

2 Answers 2

2
preg_replace('/\bi\b/', 'I', $new_string);
Sign up to request clarification or add additional context in comments.

4 Comments

This will make aaaaaa i aaaaa into aaaaaaIaaaaa
in case of " i'" is it correct preg_replace('/\bi\'/', 'I'', $new_string);
@Dani, it won't. \b is an anchor.
@Rahul Singh, the expression will replace i, ` i, i , i', ,i, etc. You don't need to adapt it in any way for i` followed by '. \b means "word boundary". Any i that is not part of a word will be replaced.
0

You could use a str_replace on the lower case string $new_string = str_replace(' i ', ' I ', $new_string). String operations are less expensive than preg for simple replacements. However, you will need one exception for every pronoun.

2 Comments

On second thoughts, preg word boundaries are a much more elegant way to find words rather than assuming whitespace. +1 to Rahul's answer.
You will also need a different str_replace() call for each possible punctuation mark that might follow the i...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.