从仅包含单词的字符串创建首字母缩略词

发布于 2024-09-18 14:10:49 字数 120 浏览 7 评论 0原文

我正在寻找一种方法,可以从输入字段中提取每个单词的第一个字母并将其放入变量中。

示例:如果输入字段为“Stack-Overflow Questions Tags Users”,则变量的输出应类似于“SOQTU”

I'm looking for a way that I can extract the first letter of each word from an input field and place it into a variable.

Example: if the input field is "Stack-Overflow Questions Tags Users" then the output for the variable should be something like "SOQTU"

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(11

国粹 2024-09-25 14:10:49
$s = 'Stack-Overflow Questions Tags Users';
echo preg_replace('/\b(\w)|./', '$1', $s);

与 codaddict 相同,但更短

  • 对于 unicode 支持,请将 u 修饰符添加到正则表达式:preg_replace('...../u',
$s = 'Stack-Overflow Questions Tags Users';
echo preg_replace('/\b(\w)|./', '$1', $s);

the same as codaddict's but shorter

  • For unicode support, add the u modifier to regex: preg_replace('...../u',
北城挽邺 2024-09-25 14:10:49

类似于:

$s = 'Stack-Overflow Questions Tags Users';

if(preg_match_all('/\b(\w)/',strtoupper($s),$m)) {
    $v = implode('',$m[1]); // $v is now SOQTU
}

我使用正则表达式 \b(\w) 来匹配紧跟在单词边界后面的单词字符

编辑:
为了确保所有缩写字符都是大写,您可以使用 strtoupper< /a> 如图所示。

Something like:

$s = 'Stack-Overflow Questions Tags Users';

if(preg_match_all('/\b(\w)/',strtoupper($s),$m)) {
    $v = implode('',$m[1]); // $v is now SOQTU
}

I'm using the regex \b(\w) to match the word-char immediately following the word boundary.

EDIT:
To ensure all your Acronym char are uppercase, you can use strtoupper as shown.

西瓜 2024-09-25 14:10:49

只是为了完全不同:

$input = 'Stack-Overflow Questions Tags Users';

$acronym = implode('',array_diff_assoc(str_split(ucwords($input)),str_split(strtolower($input))));

echo $acronym;

Just to be completely different:

$input = 'Stack-Overflow Questions Tags Users';

$acronym = implode('',array_diff_assoc(str_split(ucwords($input)),str_split(strtolower($input))));

echo $acronym;
一身软味 2024-09-25 14:10:49
$initialism = preg_replace('/\b(\w)\w*\W*/', '\1', $string);
$initialism = preg_replace('/\b(\w)\w*\W*/', '\1', $string);
殤城〤 2024-09-25 14:10:49

如果它们仅由空格 而没有其他东西分隔。您可以这样做:

function acronym($longname)
{
    $letters=array();
    $words=explode(' ', $longname);
    foreach($words as $word)
    {
        $word = (substr($word, 0, 1));
        array_push($letters, $word);
    }
    $shortname = strtoupper(implode($letters));
    return $shortname;
}

If they are separated by only space and not other things. This is how you can do it:

function acronym($longname)
{
    $letters=array();
    $words=explode(' ', $longname);
    foreach($words as $word)
    {
        $word = (substr($word, 0, 1));
        array_push($letters, $word);
    }
    $shortname = strtoupper(implode($letters));
    return $shortname;
}
你穿错了嫁妆 2024-09-25 14:10:49

Regular expression matching as codaddict says above, or str_word_count() with 1 as the second parameter, which returns an array of found words. See the examples in the manual. Then you can get the first letter of each word any way you like, including substr($word, 0, 1)

情深缘浅 2024-09-25 14:10:49

str_word_count() 函数可能会执行您的操作寻找:

$words = str_word_count ('Stack-Overflow Questions Tags Users', 1);
$result = "";
for ($i = 0; $i < count($words); ++$i)
  $result .= $words[$i][0];

The str_word_count() function might do what you are looking for:

$words = str_word_count ('Stack-Overflow Questions Tags Users', 1);
$result = "";
for ($i = 0; $i < count($words); ++$i)
  $result .= $words[$i][0];
江挽川 2024-09-25 14:10:49
function initialism($str, $as_space = array('-'))
{
    $str = str_replace($as_space, ' ', trim($str));
    $ret = '';
    foreach (explode(' ', $str) as $word) {
        $ret .= strtoupper($word[0]);
    }
    return $ret;
}

$phrase = 'Stack-Overflow Questions IT Tags Users Meta Example';
echo initialism($phrase);
// SOQITTUME
function initialism($str, $as_space = array('-'))
{
    $str = str_replace($as_space, ' ', trim($str));
    $ret = '';
    foreach (explode(' ', $str) as $word) {
        $ret .= strtoupper($word[0]);
    }
    return $ret;
}

$phrase = 'Stack-Overflow Questions IT Tags Users Meta Example';
echo initialism($phrase);
// SOQITTUME
嘿嘿嘿 2024-09-25 14:10:49
$s = "Stack-Overflow Questions IT Tags Users Meta Example";    
$sArr = explode(' ', ucwords(strtolower($s)));
$sAcr = "";
foreach ($sArr as $key) {
   $firstAlphabet = substr($key, 0,1);
   $sAcr = $sAcr.$firstAlphabet ;
}
$s = "Stack-Overflow Questions IT Tags Users Meta Example";    
$sArr = explode(' ', ucwords(strtolower($s)));
$sAcr = "";
foreach ($sArr as $key) {
   $firstAlphabet = substr($key, 0,1);
   $sAcr = $sAcr.$firstAlphabet ;
}
仙女 2024-09-25 14:10:49

使用@codaddict 的答案。

我还认为在您有一个缩写词作为要缩写的词的情况下,例如DPR而不是开发石油资源,所以这样的词将在D上 作为缩写版本,没有多大意义。

function AbbrWords($str,$amt){
        $pst = substr($str,0,$amt);
        $length = strlen($str);
        if($length > $amt){
            return $pst;
        }else{
            return $pst;
        }
    }
    
    function AbbrSent($str,$amt){
        if(preg_match_all('/\b(\w)/',strtoupper($str),$m)) {
            $v = implode('',$m[1]); // $v is now SOQTU
            if(strlen($v) < 2){
                if(strlen($str) < 5){
                    return $str;
                }else{
                    return AbbrWords($str,$amt);
                }
            }else{
                return AbbrWords($v,$amt);
            }
        }
    }

using answer from @codaddict.

i also thought in a case where you have an abbreviated word as the word to be abbreviated e.g DPR and not Development Petroleum Resources, so such word will be on D as the abbreviated version which doesn't make much sense.

function AbbrWords($str,$amt){
        $pst = substr($str,0,$amt);
        $length = strlen($str);
        if($length > $amt){
            return $pst;
        }else{
            return $pst;
        }
    }
    
    function AbbrSent($str,$amt){
        if(preg_match_all('/\b(\w)/',strtoupper($str),$m)) {
            $v = implode('',$m[1]); // $v is now SOQTU
            if(strlen($v) < 2){
                if(strlen($str) < 5){
                    return $str;
                }else{
                    return AbbrWords($str,$amt);
                }
            }else{
                return AbbrWords($v,$amt);
            }
        }
    }
会发光的星星闪亮亮i 2024-09-25 14:10:49

作为 @user187291 的 preg_replace() 模式的替代方案,这里具有相同的功能,无需在替换字符串中引用。

它的工作原理是匹配第一个出现的单词字符,然后用 \K 忘记它,然后它将匹配零个或多个单词字符,然后它将匹配零个或多个非单词字符。这将消耗所有不需要的字符,只留下第一个出现的单词字符。这是理想的,因为不需要内爆匹配数组。 u 修饰符确保正则表达式引擎将重音/多字节字符视为整个字符。

代码:(演示

$tests = [
    'Stack-Overflow Questions Tags Users',
    'Stack Overflow Close Vote Reviewers',
    'Jean-Claude Vandàmme'
];
var_export(
    preg_replace('/\w\K\w*\W*/u', '', $tests)
);

输出:

array (
  0 => 'SOQTU',
  1 => 'SOCVR',
  2 => 'JCV',
)

As an alternative to @user187291's preg_replace() pattern, here is the same functionality without needing a reference in the replacement string.

It works by matching the first occurring word characters, then forgetting it with \K, then it will match zero or more word characters, then it will match zero or more non-word characters. This will consume all of the unwanted characters and only leave the first occurring word characters. This is ideal because there is no need to implode an array of matches. The u modifier ensures that accented/multibyte characters are treated as whole characters by the regex engine.

Code: (Demo)

$tests = [
    'Stack-Overflow Questions Tags Users',
    'Stack Overflow Close Vote Reviewers',
    'Jean-Claude Vandàmme'
];
var_export(
    preg_replace('/\w\K\w*\W*/u', '', $tests)
);

Output:

array (
  0 => 'SOQTU',
  1 => 'SOCVR',
  2 => 'JCV',
)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文