preg match between two strings

I need help with this preg match. I tried this from other post but did not get the result. So finally posting it.

I am trying to extract z,a,b from first and a from second example.

1) Write a function operations with parameter z,a,b and returns b.

2) write a function factorial with parameter a.

This is what I tried so far:

 preg_match_all('/\parameter(.*?)\and?/', $question, $match);
          $questionVars = $match[1];
          print $questionVars;

Thank you so much!

1 answer

  • answered 2018-03-21 00:02 Wiktor Stribi┼╝ew

    Your solution can be different depending on actual requirements.

    If you need a string after parameter as a whole word that can consist of word and comma chars you may use

    preg_match('~\bparameter\s+\K\w+(?:\s*,\s*\w+)*~', $s, $m)

    See the regex demo. The \bparameter\s+ matches a word boundary, parameter and 1+ whitespace chars, and all this text is omitted with the help of \K, the match reset operator. \w+(?:\s*,\s*\w+)* matches and returns the 1+ word chars followed with 0+ repetitions of a comma enclosed with optional whitespace chars and again 1+ word chars.

    If you plan to get those comma-separated chunks separately, use

    preg_match_all('~(?:\G(?!^)\s*,\s*|\bparameter\s+)\K\w+~', $s, $m)

    See another regex demo. Here, (?:\G(?!^),\s*|\bparameter\s+) will either match the whole word parameter with 1+ whitespace after (\bparameter\s+, as in the previous solution) or the end of the previous successful match with , enclosed with optional whitespace chars (\G(?!^)\s*,\s*). The \K will omit the text matched so far and \w+ will grab the value. You may replace with [^,]* to grab 0+ chars other than a comma.