Find character in string

Asked

Viewed 6,834 times

4

How to find the position of a given character, where the string has many of these characters in the same string, for example: find the 3rd letter X in the string Y. some way to accomplish this?

4 answers

4

usa strpos http://php.net/manual/en/function.strpos.php

where you can make a loop by passing the $offset from where the function should start to search


Something like that

<?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);
  • but how could I find the 3rd letter X in the string Y, and I don’t know the quantity nor the position of the letter X in the string?

3


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() receives three parameters:

  1. Text to be searched (haystack)
  2. Text to be searched for (needle)
  3. Number of occurrence to be located (nth occurrence of the previous parameter), where 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 of existing occurrences the return will be false.

Run in Ideone

  • 1

    It works perfectly, thank you

2

Use the function strpos. Its parameters are:

  • $haystack: To string in which the search will be made.
  • $needle: Characters to be searched.
  • $offset: This parameter allows you to define from which character in $haystack 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

DEMO

  • but how could I find the 3rd letter X in the string Y, and I don’t know the quantity nor the position of the letter X in the string?

  • @Ricardohenrique I improved the answer.

-1

$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
  • Greetings, Andre. It’s nice that you want to contribute to the community, but it would be interesting for you to add explanations to your answer. A code that may be trivial to you may not be trivial to other users, so always try to explain by text the implemented logic.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.