Search code examples
phpstrpos

Unable to find position of the first occurrence in a string


I need to find position of the first character occurrence in a string that does not repeat. So far all I have my $pos outputs 0.

<?php
$sentence = "some long string";
$found = false;

while(!$found && $sentence!== ""){
  $c = $sentence[0];
  $count = substr_count($sentence,$c);

  if ($count == 1) $found = true;
  else $sentence = str_replace($c,"",$sentence);
}
$pos = strpos($sentence, $c);
echo "$c: $pos";

It wil output l:0. What's up with that?

I understand that $pos = strpos($sentence, $c); will not be the correct way to find position. Why Im confused is, when I echo $c its value is "l". So, I thought if i use its value in strpos it will give me the correct position. So to get help on how to extract this first non repeating character position, i thought I would ask at StackOverlow to point me to the right direction. No need to be d**ks, I just learning and I appreciate the help.


Solution

  • Your code is nearly correct. When I tested it I got 'm: 0', which is indeed the first character only to appear once. The reason the position is 0 is that you have been shrinking the original string every time you tried a new character.

    I suggest you copy the string before you start looking for characters in it, and then use the copy to calculate the position at the end, rather than the diminished string.

    <?php
    $sentence = "some long string";
    $sentence_copy = $sentence;
    $found = false;
    
    while(!$found && $sentence!== ""){
      $c = $sentence[0];
      $count = substr_count($sentence,$c);
      if ($count == 1) $found = true;
      else $sentence = str_replace($c,"",$sentence);
    }
    
    $pos = strpos($sentence_copy, $c);
    echo "$c: $pos";
    

    This gives me 'm: 2', which is correct.