1

すべての単語を大文字にしてから、 aof、. 最初と最後の単語は大文字のままにする必要があります。\b の代わりに使用してみましたが、奇妙な問題が発生しました。私も試しましたが、それは「文字列の終わりではない」という意味ではないようです\s[^$]

function titleize($string){
  return ucfirst(
     preg_replace("/\b(A|Of|An|At|The|With|In|To|And|But|Is|For)\b/uie",
     "strtolower('$1')", 
     ucwords($string))
  );
}

これは、私が修正しようとしている唯一の失敗したテストです。最後の「in」は大文字のままにする必要があります。

titleize("gotta give up, gotta give in");
//Gotta Give Up, Gotta Give In

これらのテストはパスします:

titleize('if i told you this was killing me, would you stop?');
//If I Told You This Was Killing Me, Would You Stop?

titleize("we're at the top of the world (to the simple two)");
//We're at the Top of the World (to the Simple Two)

titleize("and keep reaching for those stars");
//And Keep Reaching for Those Stars
4

3 に答える 3

1

文字列をregex-replaceに送信する前に適用ucwords()し、次にregexから戻った後に再度適用ucfirstします(文字列の先頭に表示される単語の場合)。これは、文字列の最初と最後のすべての単語が空白で囲まれないという規則によって短縮できます。この規則を使用すると、のような正規表現を使用できます。これにより、関数がどういうわけか単純化されます。'/(?<=\s)( ... )(?=\s)/'

function titleize2($str) {
 $NoUc = Array('A','Of','An','At','The','With','In','To','And','But','Is','For');
 $reg = '/(?<=\s)('      # set lowercase only if surrounded by whitespace
      . join('|', $NoUc) # add OR'ed list of words
      . ')(?=\s)/e';     # set regex-eval mode
 return preg_replace( $reg, 'strtolower("\\1")', ucwords($str) );
}

でテストした場合:

...
$Strings = Array('gotta give up, gotta give in',
                 'if i told you this was killing me, would you stop?',
                 'we\'re at the top of the world (to the simple two)',
                 'and keep reaching for those stars');

foreach ($Strings as $s)
   print titleize2($s) . "\n";
...

...これは正しい結果を返します。

于 2012-07-22T14:36:02.653 に答える
0

この正規表現を試してください:

/\b(A|Of|An|At|The|With|In|To|And|But|Is|For)(?!$)\b/uie

否定先読み(?!$)は、末尾が続く一致を除外します。

于 2012-07-22T11:31:57.820 に答える
0

行末に否定先読みを追加すると、(?!$)必要なことが行われます

function titleize($string){
  return ucfirst(
     preg_replace("/\b(A|Of|An|At|The|With|In|To|And|But|Is|For)\b(?!$)/uie",
     "strtolower('$1')", 
     ucwords(inflector::humanize($string)))
  );
}
于 2012-07-22T11:32:17.833 に答える