Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding a character at a specific position of a string

Tags:

php

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.

like image 236
Marcus Weller Avatar asked Aug 26 '13 19:08

Marcus Weller


People also ask

How do I find a character in a specific position in a string?

charAt(int position) method of String Class can be used to get the character at specific position in a String. Return type of charAt(int position) is char. Index or position is counted from 0 to length-1 characters.

How do I find a specific element in a string?

You can search for a particular letter in a string using the indexOf() method of the String class. This method which returns a position index of a word within the string if found. Otherwise it returns -1.


1 Answers

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

like image 155
Mic1780 Avatar answered Oct 19 '22 23:10

Mic1780