Finding a character at a specific position of a string

前端 未结 5 1590
眼角桃花
眼角桃花 2021-01-05 14:28

Since I am still new to PHP, I am looking for a way to find out how to get a specific character from a string.

Example:

$word = \"master\";
$length =         


        
相关标签:
5条回答
  • 2021-01-05 14:53

    Try this simply:

    $word = "master";
    $length = strlen($word);
    $random = rand(0,$length-1);
    
    if($word[$random] == 's'){
     echo $word[$random]; 
    }
    

    Here I used 0 because $word[0] is m so that we need to subtract one from strlen($word) for getting last character r

    0 讨论(0)
  • 2021-01-05 14:58

    Use substr

    $GetThis = substr($myStr, 5, 5);
    

    Just use the same values for the same or different if you want multiple characters

    $word = "master";
    $length = strlen($word);
    $random = rand(0,$length-1);
    $GetThis = substr($word, $random, $random);
    

    As noted in my comment (I overlooked as well) be sure to start your rand at 0 to include the beginning of your string since the m is at place 0. If we all overlooked that it wouldn't be random (as random?) now would it :)

    0 讨论(0)
  • 2021-01-05 15:08

    You can simply use $myStr{$random} to obtain the nth character of the string.

    0 讨论(0)
  • 2021-01-05 15:11

    You can use substr() to grab a portion of a string starting from a point and going length. so example would be:

    substr('abcde', 1, 1); //returns b
    

    In your case:

    $word = "master";
    $length = strlen($word) - 1;
    $random = rand(0,$length);
    echo substr($word, $random, 1);//echos single char at random pos
    

    See it in action here

    0 讨论(0)
  • 2021-01-05 15:12

    You can use your string the same like 0-based index array:

    $some_string = "apple";
    echo $some_string[2];
    

    It'll print 'p'.

    or, in your case:

    $word = "master";
    $length = strlen($word);
    $random = rand(0,$length-1);
    
    echo $word[$random];
    
    0 讨论(0)
提交回复
热议问题