How to get first letter of every word using regex in PHP

后端 未结 2 355
猫巷女王i
猫巷女王i 2021-01-12 10:19

I have a string variable and I want to get the first letter of every word of it. I want the end result to be an array of first letters.

$language = \'Sample          


        
相关标签:
2条回答
  • 2021-01-12 10:30

    First of all use preg_match_all for this, and secondly you don't need the + quantifier:

    $language = 'Sample Language';
    preg_match_all('/\b\w/', $language, $match);
    print_r($match);
    
    • \b: Matches a word boundary, a word boundary is a position that separates a word character from a non-word character. Word characters are usually [a-zA-Z0-9_].
    • \w: Matches a word character.
    • \b\w Matches a word character that is at a word boundary position, in this case right after the space or the start-of-string that separates the words.

    In case you want camel case situations then you can combine the previous expression with another one like this:

    \b\w|(?<=\p{Ll})\p{Lu}
    

    The second part of the expression, namely (?<=\w)\p{Lu} should match any word character if it is an uppercase character \p{Lu} following a lowercase one \p{Ll} which should cover the camel case situation, the original expressions covers the situation when a hyphen - is used to separate the two words.

    Regex101 Demo

    0 讨论(0)
  • Can you try this,

        $language = 'Sample Language';
    
        $language = explode(" ", $language);
    
        foreach ($language as $value) {
            echo $firstLetter = $value[0];
        }
    
    0 讨论(0)
提交回复
热议问题