Let\'s say I have a string.
$string = red,green,blue,yellow,black;
Now I have a variable which is the position of the word I am searching f
http://codepad.org/LA35KzEZ
$a = explode( ',', $string );
echo $a[ $key ];
Given:
$string = 'red,green,blue,yellow,black';
$key = 2;
Then (< PHP 5.4):
$string_array = explode(',', $string);
$word = $string_array[$key];
Then (>= PHP 5.4):
$word = explode(',', $string)[$key];
A better way to solve this, would be by converting the string into an array using 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];
This works by splitting a sentence into words based on word boundaries (Spaces, commas, periods, etc). It's more flexible than explode()
, unless you are only working with comma delimited strings.
For example, if str
= 'Hello, my name is dog. How are you?', and $key
= 5, You would get 'How'.
If you know that your words will be separated by commas you can do something like:
$key = 2;
$string = "red,green,blue,yellow,black";
$arr = explode(",",$string);
echo $arr[$key];