Search code examples
phpstrpos

how to get the position (strpos) using wild card search in php


Consider i have a string like this

"i dont know what i am doing abcd SDDDFDFDF fff ggg eee some texts......."

This is what i want as wild card abcd %SOMEWILDCARD% fff ggg eee

ie here i need to get the position of a in abcd ie position 28.

on googling a lot i found out this fnmatch is used to match or do wildcard searches in php, but in no link i could find what i am looking for...

Here is what i tried, i know this sound stupid

echo strpos ($strmatch,  fnmatch('abcd /*/ fff ggg eee', $strmatch));

as expected it returned nothing.


Solution

  • preg_match supports a PREG_OFFSET_CAPTURE flag which will give you the position of the found string. preg_match documentation states

    PREG_OFFSET_CAPTURE

    If this flag is passed, for every occurring match the appendant string offset will also be returned. Note that this changes the value of matches into an array where every element is an array consisting of the matched string at offset 0 and its string offset into subject at offset 1.

    Short example:

    $str = "i dont know what i am doing abcd SDDDFDFDF fff ggg eee some texts.......";
    preg_match("~abcd\s+.*?\s+fff~", $str, $matches, PREG_OFFSET_CAPTURE);
    $position = $matches[0][1];
    

    To explain the regex, I use tilde(~) as the delimiter marking the beginning and end of the RegExp. And the Regexp means, match abcd that is followed by one to unlimited blankspace characters(space, tabs etc), followed by anything, match non-greedy up to next one to unlimited blankspace characters, followed by fff.

    Now the $matches is a nested array, where the first element is an array of the whole match, where the first sub-element is the string that was matched, and the second element is the starting position of that found string.