Php call: parse pseudo-regex

I have a problem that I could not understand, but it looks like it can be fun and relatively easy for those who think in algorithms ...

If there is a symbol ?? in my search expression a symbol in it, it means that it doesn’t care if there is a previous symbol (as in regex). But I want my program to print all possible results.

Some examples: "tab? Le" should print out "table" and "fairy tale". The number of results is always 2 by the number of question marks. As another example: "carn? Ati? On" should print:

  • caraton
  • caration
  • carnaton
  • clove

I am looking for a function that will take a word with question marks and output an array with all the results ...

+4
source share
2 answers

I think such a loop should work:

$to_process = array("carn?ati?on");
$results = array();
while($item = array_shift($to_process)) {
    $pos = strpos($item,"?");
    if( $pos === false) {
        $results[] = $item;
    }
    elseif( $pos === 0) {
        throw new Exception("A term (".$item.") cannot begin with ?");
    }
    else {
        $to_process[] = substr($item,0,$pos).substr($item,$pos+1);
        $to_process[] = substr($item,0,$pos-1).substr($item,$pos+1);
    }
}
var_dump($results);
+3
source

Following your example "carn? Ati? On":

You can split a word / string into an array by "?" then the last character of each line in the array will be an optional character:

[0] => carn
[1] => ati
[2] => on

You can then create two separate capabilities (i.e. with and without this last character) for each element in the first array and map these permutations to another array. Please note that the last element should be ignored for the above conversion, since it does not apply. I would do this in the form:

[0] => [carn, car]
[1] => [ati, at]
[2] => [on]

Then I will iterate over each element in the auxiliary arrays to calculate all the different combinations.

If you're stuck with this process, just post a comment.

+4
source

Source: https://habr.com/ru/post/1532344/


All Articles