phpregexdelimitershortest

php regex between delimiter chars


I am trying to find a solution to this problem. I have a string like this "&M26&M35.45#&TN#&C150,250,10# f54f#" and I want to transform it into an array that contains all the matches that are between '&' and '#'. So in my scenario i would like to have

0: M35.45
1: TN
2: C150,250,10

I tried to do that with a regex

$haystack = "&M26&M35.45#&TN#&C150,250,10# f54f#";
if (preg_match_all("/(?<=&).*?(?=#)/s", $haystack, $result))
print_r($result[0]);

But in this way i get:

0: M26&M35.45
1: TN
2: C150,250,10

If you see, the first match contains some characters that I don't need. So I'm trying to get the shortest match between my delimiters but I don't know how. Thank you!


Solution

  • When you say "I don't need this character" - you should exclude the character from your selection. Namely, [^&]. Your resulting regex is this:

    /(?<=&)[^&]*?(?=#)/s
    

    New result is:

    Array
    (
        [0] => M35.45
        [1] => TN
        [2] => C150,250,10
    )