1

I have used a function for formatting in sentence case. My PHP script function is

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 = preg_replace( "/\bi\b/", "I", $new_string );
    //$new_string = preg_replace("/\bi\'\b/", "I'", $new_string);
    $new_string = clean_spaces( $new_string );
    $new_string = m_r_e_s( $new_string );
    return trim( $new_string );
}

Though its going well and converting whole string in sentence case. But I wish it would skip characters in single quote. Like my string HeLLO world! HOw aRE You. is converting to Hello world! How are you?, but I want to skip the content in the single quotes. Like I wish to skip words in the single quotes. 'HELLO' World and convert words in single quotes to uppercase, otherwise string should remain in sentence case.

2
  • Just a heads-up: you're going to run into all sorts of trouble here with proper nouns. Commented Nov 16, 2011 at 7:17
  • I don't think he meant that your english was poor, but rather that proper nouns should be capitalized. Commented Nov 16, 2011 at 7:30

2 Answers 2

3

You can add another simple regex callback to uppercase words in single quotes. (This is what I understood you want to do.)

$new_string = preg_replace("/'(\w+)'/e", 'strtoupper("\'$1\'")', $new_string);

If you want this to work for more than one word per quote, use [\w\s]+ in place of \w+. However that would make it more likely to fail for phrases like isn't within the text.

Sign up to request clarification or add additional context in comments.

3 Comments

Its adding slashed to the string. like \\\'HELLO\\\' world. How are you all
its adding slashes to the output.
Oh weird. Add stripslashes(...) then around the strtoupper(..)
2

Here is the compact and working solution for this task:

    $s = preg_replace_callback("~([\.!]\s*\w)|'.+?'~", function($args) {
      return strtoupper($args[sizeof($args) - 1]);
    }, ucfirst(strtolower($s)));

For following input:

    $s = "HeLLO world! HOw aRE You 'HELLo' iS QuOTed and 'AnothEr' is quoted too";

It will produce:

    Hello world! How are you 'HELLO' is quoted and 'ANOTHER' is quoted too

P.S. If you are using PHP < 5.3 you can move callback into separate function.

Comments

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.