13

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 = strlen($word);
$random = rand(1,$length);

So let's say the $random value is 3, then I would like to find out what character the third one is, so in this case the character "s". If $random was 2 I would like to know that it's a "a".

I am sure this is really easy, but I tried some substr ideas for nearly an hour now and it always fails.

Your help would be greatly appreciated.

4

5 回答 5

21

您可以使用substr()从一个点开始并持续长度来抓取字符串的一部分。所以例子是:

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

在你的情况下:

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

在此处查看实际操作

于 2013-08-26T20:01:08.300 回答
12

您可以像使用基于 0 的索引数组一样使用字符串:

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

它会打印'p'。

或者,在您的情况下:

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

echo $word[$random];
于 2013-08-26T20:03:15.223 回答
2

试试这个:

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

if($word[$random] == 's'){
 echo $word[$random]; 
}

在这里我使用 0$word[0]是因为m我们需要从中减去一个strlen($word)以获得最后一个字符r

于 2013-08-26T20:00:28.120 回答
1

利用substr

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

如果您想要多个字符,只需对相同或不同的字符使用相同的值

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

正如我在评论中指出的(我也忽略了),请务必从randat0开始包含字符串的开头,因为mis at place 0。如果我们都忽略了它不会是随机的(作为随机的?)现在会不会:)

于 2013-08-26T20:03:06.763 回答
0

您可以简单地使用$myStr{$random}来获取字符串的第 n 个字符。

于 2013-08-26T20:20:12.873 回答