Skip to content

Instantly share code, notes, and snippets.

@kobus1998
Last active February 4, 2018 19:12
Show Gist options
  • Save kobus1998/1df5b86f29352458146d33a44c17e0c2 to your computer and use it in GitHub Desktop.
Save kobus1998/1df5b86f29352458146d33a44c17e0c2 to your computer and use it in GitHub Desktop.
Capture if else if else
<?php
$pattern = "(?<if_all>(?<if>(?:if)\s*\(\s*.*\s*\)\s*\{\s*.*\s*\}\s*)\s*(?<elseif>(?:(?:else if|elseif)\s*\(\s*.*\s*\)\s*\{\s*.*\s*\}\s*){0,}+)\s*(?<else>(?:else)\s*\{\s*.*\s*\}\s*){0,1})";
$haystack = "
if(x)
{
xxxxx
}
else if (x)
{
xxxx
}
else if (x)
{
xxxx
}
else
{
xxxx
}
";
preg_match($pattern, $haystack $match);
print_r($match);
/*
Full match 0-75 `if(x)
{
xxxxx
}
else if (x)
{
xxxx
}
else if (x)
{
xxxx
}
else
{
xxxx
}`
Group 1. 0-75 `if(x)
{
xxxxx
}
else if (x)
{
xxxx
}
else if (x)
{
xxxx
}
else
{
xxxx
}`
Group 2. 0-17 `if(x)
{
xxxxx
}
`
Group 3. 17-61 `else if (x)
{
xxxx
}
else if (x)
{
xxxx
}
`
Group 4. 61-75 `else
{
xxxx
}`
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment