Skip to content
Advertisement

How to find the first occurance of a few different Strings in a String in PHP

I have a String that always starts with many As, Bs or Cs and then at one point changes to Ns, Ss and Ts. I need to find the position where it changes and seperate it there.

Examples: "AAABCBACAANNNTTT", "BCBATTNTT", "AAABCBACAASSSSSS"

Output I want: "AAABCBACAA", "NNNTSTT";   "BCBA","TTNTT";   "AAABCBACAA","SSSSSS"

Now of course the position where to split would be quite easy to find with strpos if it were only one letter, like:

$string = "AAABCBACAANNNTTT";
echo(strpos($string, "S")); //Return: 13

To do it with the 3 letters, I tried the following:

$string = "AAABCBACAANNNTTT";
echo(min(strpos($string, "N"), strpos($string, "S"), strpos($string, "T"))); //Return:

The problem with this is when a letter doesn’t exist in a String it will give out an empty result.

I also found a similar question but the “best answer” doesn’t actually work, like 2 commenters on the answer note:

Find position first occurence of an array of strings in a string

Advertisement

Answer

You can do it with strpos and min function:

function str_array_pos($string, $array) {
    $pos = strlen($string);
    foreach($array as $char) {
        if($p = strpos($string, $char)) {
            $pos = min($pos, $p);
        }
    }
    
    return $pos < strlen($string) ? $pos : false;
}

This will give you the split position by looking up the positions for each provided character and return the min position or false if there is none of the characters in the string.

Input Array: ["N", "S", "T"]

Input Strings: "AAABCBACAANNNTTT", "BCBATTNTT", "AAABCBACAASSSSSS"

Outputs: 10, 4, 10

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement