-5

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 for.

$key = 2;

I want to get the word with the position of 2. In this case, the answer would be blue.

dda
  • 6,030
  • 2
  • 25
  • 34
Joe
  • 1,605
  • 7
  • 26
  • 34

5 Answers5

7

http://codepad.org/LA35KzEZ

$a = explode( ',', $string );
echo $a[ $key ];
biziclop
  • 14,466
  • 3
  • 49
  • 65
1

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.
Starx
  • 77,474
  • 47
  • 185
  • 261
1
<?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'.

Brandon
  • 16,382
  • 12
  • 55
  • 88
0

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];
iambriansreed
  • 21,935
  • 6
  • 63
  • 79
  • 1
    Note: array dereferencing (i.e., `explode(...)[$key]`) will only work in PHP 5.4 or greater. Prior to 5.4, it would need to be on two lines (i.e., `$words = explode(...); $word = $words[$key];` – Wiseguy Jul 09 '12 at 16:07
  • @Wiseguy Thats why I changed it. I have been in c# land too long. – iambriansreed Jul 09 '12 at 16:08
  • 1
    Nice; you were changing it as I was writing that comment. It _does_ work as of 5.4.0, so your code wasn't wrong, but many (most?) people are still using older versions. – Wiseguy Jul 09 '12 at 16:10
  • @Wiseguy Including me. I had no idea they were implementing it on 5.4.0. Very cool. – iambriansreed Jul 09 '12 at 16:11
0

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];
WhoaItsAFactorial
  • 3,538
  • 4
  • 28
  • 45