My problem is that I need to be able to obtain the location of the same character in a string, that is, locate the position of several characters that are equal to the same character. Example:
$string='Hola como estas, Hola estas bien y Hola porque no respondes';
From this String I want to get all the positions of Hello.
Investigating I found a method:
strpos()
But this one only allows to get the position of the first instance of the search character or sub-string , i.e. it would only allow me to search for Hello only once and not three times.
I found another method:
substr_count()
This allows me to obtain the number of times the character or sub-string is repeated in a string, that is, the number or amount of Hello in this case would be 3 .
Regardless, I don't think of a way to use both methods to achieve my goal, or simply use one that does both .
Thank you and I look forward to your response.
You can implement the
strpos_recursive
shared function in the PHP Manual contribution notes .It would be this:
And to use it:
Departure:
As you can see, the function returns an array with the positions where the word was found (it also works for a character, of course).
There you would have the two information you are looking for. Doing a
count($out);
you would know how many times the data is repeated. And reading the array you would know the positions of each occurrence of the data.You can use the str_word_count() function , which among other things,
Combining this with the key function , we can get the position value for the desired word.
A simple example of this implementation would be:
As you can see, we loop through the array element by element using the current() function . For each element of the array, we compare the value of the element with the word searched for, if there is a match, the value of said match is printed
key
, which corresponds to the position in which our word appears in thestring
original.I hope it is what you were looking for.
In any case, I would recommend you to use "explode" you separate the entire string in the word you are looking for, and then you join it, to know the positions, you only count the length of what you separated, the other idea is to use a simpler method and that It would be to go through the entire string in search of the word "Hello" with a substring, and you compare the current position.
Example: