Find the exact word position in string

后端 未结 5 1218
一个人的身影
一个人的身影 2020-12-22 15:28

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

相关标签:
5条回答
  • 2020-12-22 15:55

    http://codepad.org/LA35KzEZ

    $a = explode( ',', $string );
    echo $a[ $key ];
    
    0 讨论(0)
  • 2020-12-22 16:02

    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];
    
    0 讨论(0)
  • 2020-12-22 16:16

    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.
    
    0 讨论(0)
  • 2020-12-22 16:22
    <?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'.

    0 讨论(0)
  • 2020-12-22 16:22

    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];
    
    0 讨论(0)
提交回复
热议问题