Search code examples
phpregexpreg-match

how to match step by step


I have a string variable that gets bigger by concatenation. I need to validate every substring (every loop iteration).

I created a pattern to match the final valid form of the string.

How can I validate every substring (partial but in correct order) of the string ?

    $pattern = "#\{/?MYTAG(\d*)?\}#i" 
    $myString = ''

    while (true) {
     $myString .= $aChar;

      // {    => valid
      // {m   => valid
      // {my  => valid
      // {myz => invalid break the loop

      if ( preg_match($pattern, $myString) ) {

       }
    }

I tried to use the ? modified to make the character optional. But then it matches the partial string:

// {mysdf
// it matches {my
// I want to return false, not get the valid part of the string

I hope this makes sense.


Solution

  • If you want to test to see if the string you have so far is valid, but the regex only matches the final string, then why not add the remaining characters of the final string and test on each iteration?

    If the current string you have is "my" and you are searching for "mytag", then concatenate "mytag".substring(2) to "my" to create the final string. If the regex matches the concatenated string, then you know the string you have so far is valid.

    Ignore the specific substring() function I have up there -- it's just some pseudocode.

    Here's a more complete example (which doesn't use PHP's actual substring method -- I have not actually gone and looked it up):

    $pattern = "#\{/?MYTAG(\d*)?\}#i";
    $myString = '';
    $counter = 0;
    $finalString = "MYTAG";
    
    while (true) {
     $myString .= $aChar;
    
      // {    => valid
      // {m   => valid
      // {my  => valid
      // {myz => invalid break the loop
    
      if ( preg_match($pattern, $myString . $finalString.substring($counter + 1)) ) {
    
       }
       $counter++;
    }
    

    The major downside is this only works if you know the final string beforehand, but it seems like you do. But other than that this could serve as a nice little workaround. Please once again note that the specific substring function I used is pseudocode -- I did not actually look up the PHP substring function, but I know one exists.

    EDIT: Oops, I didn't see @arkascha's comment before posting this. This is an example of what they are talking about, though.