Ad Code

Ticker

6/recent/ticker-posts

How to find a position of character in a string in PHP without using strpos function

 Here we figure out how to perform strpos() function works to find out the first occurrence of any words in a string, but the condition was that do not use strpos() then how to do those things without it.

How to find a position of character in a string in PHP without using strpos function


If you are trying to figure out how something like strpos() could work behind the scenes, here is a very basic example that only uses basic language.

function custom_strpos ($haystack, $needle, $offset = 0) {

    // for loop with indexes for both strings, up to the length of $haystack
    for ($h_index=$offset, $n_index=0; isset($haystack[$h_index]); $h_index++, $n_index++) {

        if ($haystack[$h_index] == $needle[$n_index]) {           // *CHARACTERS MATCH*

            if (!isset($start_pos)) $start_pos = $h_index;        // set start_pos if not set

            if (!isset($needle[$n_index + 1])) return $start_pos; // all characters match


        } else {                                                  // *CHARACTERS DON'T MATCH*

            $n_index = -1;                                        // reset $needle index

            unset($start_pos);                                    // unset match start pos.
        }
    }
    // all charactes of $haystack iterated without matching $needle
    return false;
}
This is the native implementation for strpos alternatives.

If you want to understand strpos does work behind the scenes here is s a great article about how to understand the PHP source of any functions.

Also, you can use another alternatives function rather than strpos, like strstr function, this function also works similarly.

<?php 
   $str = "How are you?";
   $find = "are";
// Returns false if given words is not inside string
   strstr($str, $find);
?>

Post a Comment

0 Comments

Ad Code