入力フィールドから各単語の最初の文字を抽出して変数に入れる方法を探しています。
例: 入力フィールドが の場合"Stack-Overflow Questions Tags Users"、変数の出力は次のようになります。"SOQTU"
$s = 'Stack-Overflow Questions Tags Users';
echo preg_replace('/\b(\w)|./', '$1', $s);
codaddic と同じですが、短いです
u正規表現に修飾子を追加します。preg_replace('...../u', 何かのようなもの:
$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、示されているように使用できます。
完全に異なるために:
$input = 'Stack-Overflow Questions Tags Users';
$acronym = implode('',array_diff_assoc(str_split(ucwords($input)),str_split(strtolower($input))));
echo $acronym;
$initialism = preg_replace('/\b(\w)\w*\W*/', '\1', $string);
それらが他のものではなくスペースだけで区切られている場合。これはあなたがそれを行う方法です:
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;
}
上記の codaddict の正規表現マッチング、またはstr_word_count()を12 番目のパラメーターとして使用すると、見つかった単語の配列が返されます。マニュアルの例を参照してください。次に、次のように、好きな方法で各単語の最初の文字を取得できます。substr($word, 0, 1)
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
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];