Tomi Seus
Tomi Seus

Reputation: 1161

How to make ucwords work for single quotes only and not apostrophes?

I want to turn this text:

She's saying it's time to 'find a solution'.

into this text:

She's Saying It's Time To 'Find A Solution'.

I'm currently using both ucwords and this ucwords-related function to make capital letters after single quotes: (I found in the comment section of php.net.)

function ucwordsMore ($str) {
    $str = str_replace("' ","'",ucwords(str_replace("'","' ",$str)));
    return $str;
}

However, this function results in this:

She'S Saying It'S Time To 'Find A Solution'.

How can I best keep letters after apostrophes small, and letters after single quotes big?

Upvotes: 1

Views: 1262

Answers (3)

jakx
jakx

Reputation: 758

Sorry but there is no difference between a single quote and an apostrophe. You are going to have to use something to differentiate the two if that makes sense. A heuristic you can use is if there are only one or two consecutive chars after the apostrophe you can assume it's a contraction and not a singly quoted string.

EDIT: This is a stupid heuristic that I don't recommend but I did it anyways.

function ucwordsMore ($str) {
    $str = str_replace("' ","'",ucwords(str_replace("'","' ",$str)));
    return $str;
}

$string  = "She's Saying It's Time To 'Find A Solution'.";

$string = ucwordsMore($string);
//string now equals = She'S Saying It'S Time To 'Find A Solution'.
for($i = 0; $i < strlen($string); $i++){
    if($string[$i] == "'"){
      if($i +2 < strlen($string) && $string[$i] == "'"&& $string[$i+1] != " "&& $string[$i+2] == " "){
          $string[$i+1] = strtolower($string[$i+1]); //replace
    }
      if($i +3 < strlen($string) && $string[$i] == "'"&& $string[$i+1] != " "&& $string[$i+2] != " "&& $string[$i+3] == " "){
          $string[$i+1] = strtolower($string[$i+1]); //replace
          $string[$i+2] = strtolower($string[$i+2]); //replace
    }

}
}
echo $string;
//$string - "She's Saying It's Time To 'Find A Solution'."

Upvotes: 0

FtDRbwLXw6
FtDRbwLXw6

Reputation: 28881

$str = ucwords($str);

$str = preg_replace_callback("/(^|\\s+)'[a-z]/", create_function(
    '$matches',
    'return strtoupper($matches[0]);'
), $str);

Upvotes: -1

mario
mario

Reputation: 145472

It usually works with a bit of pattern matching:

$str = preg_replace("/\w[\w']*/e", "ucwords('\\0')", $str);

\w is okay for ASCII letters and numbers. For international text use \pL and the /u modifier.

Upvotes: 4

Related Questions