ucwords function with exceptions

前端 未结 5 2240
你的背包
你的背包 2020-12-17 05:47

I need some help i have this code that Uppercase the first character of each word in a string with exceptions i need the function to ignore the exception if it\'s at the beg

5条回答
  •  甜味超标
    2020-12-17 06:05

    preg_replace_callback() will allow you to express your conditional replacement logic in a loopless and dynamic fashion. Consider this approach that will suitably modify your sample data:

    Code: (PHP Demo) (Pattern Demo)

    $string = "my cat is going to the vet";
    $ignore = array("my", "is", "to", "the");
    $pattern = "~^[a-z]+|\b(?|" . implode("|", $ignore) . ")\b(*SKIP)(*FAIL)|[a-z]+~";
    echo "$pattern\n---\n";
    echo preg_replace_callback($pattern, function($m) {return ucfirst($m[0]);}, $string);
    

    Output:

    ~^[a-z]+|\b(?|my|is|to|the)\b(*SKIP)(*FAIL)|[a-z]+~
    ---
    My Cat is Going to the Vet
    

    You see, the three piped portions of the pattern (in order) make these demands:

    1. If the start of the string is a word, capitalize the first letter.
    2. If a "whole word" (leveraging the \b word boundary metacharacter) is found in the "blacklist", disqualify the match and keep traversing the input string.
    3. Else capitalize the first letter of every word.

    Now, if you want to get particular about contractions and hyphenated words, then you only need to add ' and - to the [a-z] character classes like this: [a-z'-] (Pattern Demo)

    If anyone has a fringe cases that will break my snippet (like "words" with special characters that need to be escaped by preg_quote()), you can offer them and I can offer a patch, but my original solution will adequately serve the posted question.

提交回复
热议问题