文字列から変数の最初の単語を抽出したいと思います。たとえば、次の入力を取ります。
<?php $myvalue = 'Test me more'; ?>
結果の出力はTest
、入力の最初の単語である、である必要があります。これどうやってするの?
文字列から変数の最初の単語を抽出したいと思います。たとえば、次の入力を取ります。
<?php $myvalue = 'Test me more'; ?>
結果の出力はTest
、入力の最初の単語である、である必要があります。これどうやってするの?
いくつかの区切り文字に基づいて文字列をより小さな文字列(トークン)に分割するために使用できる文字列関数(strtok )があります。このスレッドの目的のために、の最初の単語(最初のスペース文字の前にあるものとして定義される)は、スペース文字の文字列をトークン化することによって取得できます。Test me more
<?php
$value = "Test me more";
echo strtok($value, " "); // Test
?>
詳細と例については、strtokPHPのマニュアルページを参照してください。
explode関数は次のように使用できます。
$myvalue = 'Test me more';
$arr = explode(' ',trim($myvalue));
echo $arr[0]; // will print Test
もう一つの例:
$sentence = 'Hello World this is PHP';
$abbreviation = explode(' ', trim($sentence ))[0];
echo $abbreviation // will print Hello
PHP5.3をお持ちの場合
$myvalue = 'Test me more';
echo strstr($myvalue, ' ', true);
$myvalue
この場合、が1つの単語を含む文字列の場合、strstr
何も返されないことに注意してください。解決策は、テスト文字列にスペースを追加することです。
echo strstr( $myvalue . ' ', ' ', true );
文字列に単語が1つしかない場合でも、常に文字列の最初の単語が返されます
別の方法は次のようなものです。
$i = strpos($myvalue, ' ');
echo $i !== false ? $myvalue : substr( $myvalue, 0, $i );
または、それを使用して非常に多くの答えがあるexplodeを使用して、私はそれを行う方法をわざわざ指摘しません。
あなたができる
echo current(explode(' ',$myvalue));
少し遅れていますが、PHPにはこれに対するより良い解決策が1つあります。
$words=str_word_count($myvalue, 1);
echo $words[0];
受け入れられた回答と同様ですが、ステップが1つ少なくなります。
$my_value = 'Test me more';
$first_word = explode(' ',trim($my_value))[0];
//$first_word == 'Test'
文字列が単語で始まるかどうかわからない場合に備えて...
$input = ' Test me more ';
echo preg_replace('/(\s*)([^\s]*)(.*)/', '$2', $input); //Test
分割関数を使用すると、文字列から最初の単語を取得することもできます。
<?php
$myvalue ="Test me more";
$result=split(" ",$myvalue);
echo $result[0];
?>
<?php
$value = "Hello world";
$tokens = explode(" ", $value);
echo $tokens[0];
?>
explodeを使用して、入力のすべての単語を取得し、結果の配列の最初の要素を出力します。
$string = ' Test me more ';
preg_match('/\b\w+\b/i', $string, $result); // Test
echo $result;
/* You could use [a-zA-Z]+ instead of \w+ if wanted only alphabetical chars. */
$string = ' Test me more ';
preg_match('/\b[a-zA-Z]+\b/i', $string, $result); // Test
echo $result;
よろしく、Ciul
$ input="もっとテストしてください"; echo preg_replace( "/\s。*$/"、 ""、$ input); // "テスト"
個人的にstrsplit
//単語の境界をサポートしていないため、より正確な分割を行うには、正規表現を使用しますexplode
。strtok
\w
preg_split('/[\s]+/',$string,1);
これにより、境界のある単語が1の制限に分割されます。
これらのそれぞれの関数の速度を知りたい場合は、PHP 7.3で、ここで最も投票された6つの回答(、、、、、、、および)に対して大まかなベンチマークを実行し、それぞれ1,000,000回の反復でstrpos
速度substr
を比較しました。explode
current
strstr
explode
trim
str_word_count
strtok
<?php
$strTest = 'This is a string to test fetching first word of a string methods.';
$before = microtime(true);
for ($i=0 ; $i<1000000 ; $i++) {
$p = strpos($strTest, ' ');
$p !== false ? $strTest : substr( $strTest, 0, $p );
}
$after = microtime(true);
echo 'strpos/ substr: '.($after-$before)/$i . ' seconds<br>';
$before = microtime(true);
for ($i=0 ; $i<1000000 ; $i++) {
strstr($strTest, ' ', true);
}
$after = microtime(true);
echo 'strstr: '.($after-$before)/$i . ' seconds<br>';
$before = microtime(true);
for ($i=0 ; $i<1000000 ; $i++) {
current(explode(' ',$strTest));
}
$after = microtime(true);
echo 'explode/ current: '.($after-$before)/$i . ' seconds<br>';
$before = microtime(true);
for ($i=0 ; $i<1000000 ; $i++) {
$arr = explode(' ',trim($strTest));
$arr[0];
}
$after = microtime(true);
echo 'explode/ trim: '.($after-$before)/$i . ' seconds<br>';
$before = microtime(true);
for ($i=0 ; $i<1000000 ; $i++) {
str_word_count($strTest, 1);
}
$after = microtime(true);
echo 'str_word_count: '.($after-$before)/$i . ' seconds<br>';
$before = microtime(true);
for ($i=0 ; $i<1000000 ; $i++) {
strtok($value, ' ');
}
$after = microtime(true);
echo 'strtok: '.($after-$before)/$i . ' seconds<br>';
?>
2回の連続実行によるさまざまな結果は次のとおりです。
strpos/ substr: 6.0736894607544E-8 seconds
strstr: 5.0434112548828E-8 seconds
explode/ current: 3.5163116455078E-7 seconds
explode/ trim: 3.8683795928955E-7 seconds
str_word_count: 4.6665270328522E-6 seconds
strtok: 4.9849510192871E-7 seconds
strpos/ substr: 5.7171106338501E-8 seconds
strstr: 4.7624826431274E-8 seconds
explode/ current: 3.3753299713135E-7 seconds
explode/ trim: 4.2293286323547E-7 seconds
str_word_count: 3.7025549411774E-6 seconds
strtok: 1.2249300479889E-6 seconds
そして、関数の順序を逆にした後の結果:
strtok: 4.2612719535828E-7 seconds
str_word_count: 4.1899878978729E-6 seconds
explode/ trim: 9.3175292015076E-7 seconds
explode/ current: 7.0811605453491E-7 seconds
strstr: 1.0137891769409E-7 seconds
strpos/ substr: 1.0082197189331E-7 seconds
結論これらの機能間の速度は大きく異なり、テストの実行間で期待するほど一貫性がないことがわかりました。これらの迅速で汚いテストによると、選択された6つの機能のいずれも、妥当な時間内に作業を完了します。実行時間に干渉している実行中の他のプロセスを含む摂動があります。したがって、プログラマーとして最も実用的で読みやすい機能を使用するだけです。プログラミングの全体像については、 DonaldKnuthの文芸的プログラミングを参照してください。
$ first_word = str_word_count(1)[0]
特殊文字では機能しません。特殊文字を使用すると、誤った動作が発生します。UTF-8に対応していません。
あなたの質問は、「文字列の最初のスペースとそれに続くすべてのものを何も置き換えない」と再定式化することができます。したがって、これは単純な正規表現で実現できます。
$firstWord = preg_replace("/\s.*/", '', ltrim($myvalue));
安全のためにltrim()へのオプションの呼び出しを追加しました。この関数は文字列の先頭のスペースを削除します。