How do I print the position of 2 letters in a word? for eg, print strpos("arya","a");?


#1


Replace this line with your code.


#2

Could you show me your full code and task that is given to you?


#3

Hi elv1nas,

Thanks for replying , it's a query that I had while I was solving the string function task.

The task is to find the position of a letter in a word for which the example given was
print strpos("emily", "i"); // It's a 1 line code

the o/p is 2.

My question is what if the word is 'aarya' or 'arya' ,and I want to find the position of all the a's present in the word , another similar example can be 'BOB',
when I type , print strpos("BOB");
The output is 0 ,i.e. Zero is the position of the first B, my question is "What is the code for showing the position of B as 0 and 2 ?" ,as there are 2 B's in the word bob.


#4

Syntax:

strpos(string,find,start)

string      Required. Specifies the string to search
find	    Required. Specifies the string to find
start	    Optional. Specifies where to begin the search

<?php
// We can search for the character, ignoring anything before the offset
$text = 'bob';
$pos = strpos($text, 'b', 2); // $pos = 2, not 0
?>

check it here for more details


#5

@shreyasta Good question!


#6

Unfortunately as far as I know there isn't PHP function that can find all positions of a character in a string.

So I came up with quick solution (and this is not necessarily the best solution):

$haystack = 'aarya';
$needle = 'a';
$lastPos = 0;

$pos = 0;

$pos = strpos($haystack, $needle, $pos);
do {
	echo $pos . "\r";
	$pos = $pos + strlen($needle);
} while(($pos = strpos($haystack, $needle, $pos)) !== FALSE);

Firstly, we start searching first position starting at position 0, then in do block we echo out position of that letter after that we increase $pos number by adding $pos (itself) and length of a needle together
this way we get a new position from which to start searching for next position.
While loop keeps working until condition is true or in other words until we find
next position of that letter and if the outcome is not identical to FALSE we know that
next position is found and that evaluates to TRUE and we repeat the same process in do block.

You can do it however you like it with do...while, while, for loop or even foreach.

It's worth mentioning that strpos is case sensitive so if you try to find all lowercase a's letters and your string contains only uppercase letters then positions won't be found. You can use stripos function the same as strpos but case-insensitive version if you want to find position of a letter without worrying if it is in lowercase or uppercase.

If you want to find positions or occurrences of more unusual letters like - èéåä then you should use multibyte string functions they're prefixed with mb_ you can find out more about it on php.net manual.


#7

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.