phpregexpreg-match-allsubstringoverlapping-matches

Find all substrings within a string with overlap


Hi im trying to find all overlapping substrings in a string here is my code its only finding nonrepeating ACA.

$haystack = "ACAAGACACATGCCACATTGTCC";
$needle = "ACA";
echo preg_match_all("/$needle/", $haystack, $matches);

Solution

  • You're using echo to print the return value of preg_match_all. That is, you're displaying only the number of matches found. What you probably wanted to do was something like print_r($matches);, like this:

    $haystack = "ACAAGACACATGCCACATTGTCC";
    $needle = "ACA";
    preg_match_all("/$needle/", $haystack, $matches);
    print_r($matches);
    

    Output:

    Array
    (
        [0] => Array
            (
                [0] => ACA
                [1] => ACA
                [2] => ACA
            )
    
    )
    

    Demo

    If your real concern is that it counted ACACA only once, well, there are three things that need to be said about that:

    1. That's basically unavoidable with regex.
    2. You really shouldn't count this twice, as it's overlapping. It's not a true recurrence of the pattern.
    3. That said, if you want to count that twice, you could do so with something like this:

      echo preg_match_all("/(?=$needle)/", $haystack, $matches);
      

      Output:

      4
      

      Demo