文字列があるとしましょう。
$string = red,green,blue,yellow,black;
これで、検索している単語の位置である変数ができました。
$key = 2;
位置が2の単語を取得したいのですが、この場合、答えは。になりますblue
。
文字列があるとしましょう。
$string = red,green,blue,yellow,black;
これで、検索している単語の位置である変数ができました。
$key = 2;
位置が2の単語を取得したいのですが、この場合、答えは。になりますblue
。
$a = explode( ',', $string );
echo $a[ $key ];
これを解決するためのより良い方法は、explode()を使用して文字列を配列に変換することです。
$string = ...;
$string_arr = explode(",", $string);
//Then to find the string in 2nd position
echo $string_arr[1]; //This is given by n-1 when n is the position you want.
<?php
$string = preg_split( '/[\s,]+/', $str );
echo $string[$key];
これは、単語の境界(スペース、コンマ、ピリオドなど)に基づいて文を単語に分割することで機能します。explode()
カンマ区切りの文字列のみを操作している場合を除いて、よりも柔軟性があります。
たとえば、str
='こんにちは、私の名前は犬です。「お元気ですか?」、$key
= 5、「お元気ですか」を取得します。
与えられた:
$string = 'red,green,blue,yellow,black';
$key = 2;
次に(<PHP 5.4):
$string_array = explode(',', $string);
$word = $string_array[$key];
次に(> = PHP 5.4):
$word = explode(',', $string)[$key];
単語がコンマで区切られることがわかっている場合は、次のようにすることができます。
$key = 2;
$string = "red,green,blue,yellow,black";
$arr = explode(",",$string);
echo $arr[$key];