14

入力フィールドから各単語の最初の文字を抽出して変数に入れる方法を探しています。

例: 入力フィールドが の場合"Stack-Overflow Questions Tags Users"、変数の出力は次のようになります。"SOQTU"

4

10 に答える 10

22
$s = 'Stack-Overflow Questions Tags Users';
echo preg_replace('/\b(\w)|./', '$1', $s);

codaddic と同じですが、短いです

  • Unicodeをサポートするには、u正規表現に修飾子を追加します。preg_replace('...../u',
于 2010-09-09T16:11:16.597 に答える
17

何かのようなもの:

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

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

正規表現を使用して、単語の境界の直後にある word-char\b(\w)と一致させています。

編集:すべての頭字語文字が大文字であることを確認するにはstrtoupper、示されているように使用できます。

于 2010-09-09T15:00:27.313 に答える
6

完全に異なるために:

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

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

echo $acronym;
于 2010-09-09T15:36:10.940 に答える
5
$initialism = preg_replace('/\b(\w)\w*\W*/', '\1', $string);
于 2010-09-09T15:02:21.880 に答える
4

それらが他のものではなくスペースだけで区切られている場合。これはあなたがそれを行う方法です:

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;
}
于 2010-09-09T15:00:45.143 に答える
3

上記の codaddict の正規表現マッチング、またはstr_word_count()12 番目のパラメーターとして使用すると、見つかった単語の配列が返されます。マニュアルの例を参照してください。次に、次のように、好きな方法で各単語の最初の文字を取得できます。substr($word, 0, 1)

于 2010-09-09T15:02:19.867 に答える
2
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
于 2010-09-09T15:23:40.060 に答える
2

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];
于 2010-09-09T15:04:06.293 に答える