How to find the position of a given character, where the string has many of these characters in the same string, eg find the 3rd letter X in the string Y. some way to do this?
How to find the position of a given character, where the string has many of these characters in the same string, eg find the 3rd letter X in the string Y. some way to do this?
This calls for a specialized function. Well, I quickly developed the following:
function nthstrpos($haystack, $needle, $nth) {
$count = 0;
$pos = -1;
do {
$pos = strpos($haystack, $needle, $pos + 1);
$count++;
} while ($pos !== false && $count < $nth);
return $pos;
}
The function nthstrpos()
gets three parameters:
1
the first occurrence and so on For example, the command nthstrpos('banana', 'a', 2)
will return the second occurrence of the letter a
in the text banana
.
If the text to be searched is not found or the number of the requested occurrence exceeds the total number of occurrences, the return will be false
.
use strpos link
You can loop through the $ offset from where the function should start fetching
Something like this
<?php
$texto = "um texto muito longo cheio de letras, numeros, fatos, historias, aventuras e altas confusões na sessao da tarde.";
$achar = "a";
$posicoes = array();
$offset = 0;
while ( ($pos = strpos($texto, $achar, $offset)) !== false) {
$posicoes[] = $pos;
$offset = $pos+1;
}
print_r($posicoes);
Update
If you want you can also use regular expressions, which in my opinion is much more elegant:
<?php
$re = "/a/";
$str = "um texto muito longo cheio de letras, numeros, fatos, historias, aventuras e altas confusões na sessao da tarde.";
preg_match_all($re, $str, $resultados, PREG_OFFSET_CAPTURE);
print_r($resultados);
Use the strpos
function. Its parameters are:
$haystack
: The string where the search will be done. $needle
: Characters to fetch. $offset
: This parameter allows you to define from which character in $haystack
to start the search. We can use this last parameter to do this type of search, like this:
function strposNth($texto, $procurar, $n){
switch($n){
case $n === 0:
return false;
break;
case $n === 1:
return(strpos($texto, $encontrar) + 1);
break;
default:
return(strpos($texto, $procurar, strposNth($texto, $procurar, $n - 1) +
strlen($procurar)) + 1);
break;
}
}
To use it:
echo strposNth("overflow", "o", 2); // 7
$test = "Hi, How are you!";
function strCharFind($needle,$haystack){
$return = FALSE;
$arr = str_split($haystack,1);
foreach($arr as $value){
if($value==strtolower($needle)||$value==strtoupper($needle)){
$return = TRUE;
}
}
return $return;
}
var_dump(strCharFind(',',$test));//true
var_dump(strCharFind('h',$test));//true
var_dump(strCharFind('!',$test));//true
var_dump(strCharFind('?',$test));//false