Ik moet een reeks woorden doorzoeken tegen een woordenwoordenboek (txt-bestand) en elk woord dat niet gevonden is, kapitaliseren.
I'm trying to split the string into an array of words and check them against the unix /usr/dict/words dictionary. If a match is found for the word it gets lcfirst($word)
if no match then ucfirst( $word )
Het woordenboek wordt geopend en in een array geplaatst met behulp van fgetcsv (ik heb ook geprobeerd om fgets te gebruiken en te exploderen aan het einde van de regel).
function wnd_title_case( $string ) {
$file = fopen( "/users/chris/sites/wp-dev/trunk/core/words.txt", "rb" );
while ( !feof( $file ) ) {
$line_of_text = fgetcsv( $file );
$exceptions = array( $line_of_text );
}
fclose( $file );
$delimiters = array(" ", "-", "O'");
foreach ( $delimiters as $delimiter ) {
$words = explode( $delimiter, $string );
$newwords = array();
foreach ($words as $word) {
if ( in_array( strtoupper( $word ), $exceptions ) ) {
//check exceptions list for any words that should be lower case
$word = lcfirst( $word );
} elseif ( !in_array( $word, $exceptions ) ) {
//everything else capitalized
$word = ucfirst( $word );
}
array_push( $newwords, $word );
}
$string = join( $delimiter, $newwords );
}
$string = ucfirst( $string );
return $string;
}
Ik heb geverifieerd dat het bestand wordt geopend.
The desired output: Sentence case title string with proper nouns capitalized.
The current output: Title string with every word capitalized
Bewerk:
Met behulp van het antwoord van Jay hieronder kwam ik met een werkbare oplossing. Mijn eerste probleem was dat mijn woordenwoordenboek zowel hoofdletters als niet-hoofdletterwoorden bevatte, dus ik vond een eigen namenwoordenboek om te controleren of ik een regex-callback gebruikte. Het is niet perfect, maar krijgt het meestal goed.
function title_case( $string ) {
$fp = @fopen( THEME_DIR. "/_/inc/propernames", "r" );
$exceptions = array();
if ( $fp ) {
while( !feof($fp) ) {
$buffer = fgets( $fp );
array_push( $exceptions, trim($buffer) );
}
}
fclose( $fp );
$content = strtolower( $string );
$pattern = '~\b' . implode ( '|', $exceptions ) . '\b~i';
$content = preg_replace_callback ( $pattern, 'regex_callback', $content );
$new_content = $content;
return ucfirst( $new_content );
}
function regex_callback ( $data ) {
if ( strlen( $data[0] ) > 3 )
return ucfirst( strtolower( $data[0] ));
else return ( $data[0] );
}