php 在字符串的特定位置查找字符
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18452024/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Finding a character at a specific position of a string
提问by Marcus Weller
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.
由于我还是 PHP 的新手,我正在寻找一种方法来找出如何从字符串中获取特定字符。
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".
所以假设 $random 值是 3,那么我想找出第三个是什么字符,所以在这种情况下是字符“s”。如果 $random 是 2,我想知道它是一个“a”。
I am sure this is really easy, but I tried some substr ideas for nearly an hour now and it always fails.
我相信这真的很容易,但我尝试了近一个小时的 substr 想法,但总是失败。
Your help would be greatly appreciated.
您的帮助将不胜感激。
回答by Mic1780
You can use substr()
to grab a portion of a string starting from a point and going length. so example would be:
您可以使用substr()
从点和长度开始抓取字符串的一部分。所以例子是:
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
在这里看到它的行动
回答by Przemys?aw Kalita
You can use your string the same like 0-based index array:
您可以像使用基于 0 的索引数组一样使用字符串:
$some_string = "apple";
echo $some_string[2];
It'll print 'p'.
它会打印“p”。
or, in your case:
或者,就您而言:
$word = "master";
$length = strlen($word);
$random = rand(0,$length-1);
echo $word[$random];
回答by Marcus Weller
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,因为$word[0]
是m
这样,我们需要减一strlen($word)
用于获取最后一个字符r
回答by sealz
Use substr
用 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 :)
正如我在评论中所指出的(我也忽略了),请务必以rand
at0
开头以包含字符串的开头,因为 the m
is at place 0
。如果我们都忽略了它不会是随机的(作为随机的?)现在是吗:)
回答by keanpedersen
You can simply use $myStr{$random}
to obtain the nth character of the string.
您可以简单地使用$myStr{$random}
获取字符串的第 n 个字符。