Skip to content

Instantly share code, notes, and snippets.

@imme-emosol
Last active July 3, 2020 07:38
Show Gist options
  • Save imme-emosol/450f604fce19b8ae858dd84ace5cc339 to your computer and use it in GitHub Desktop.
Save imme-emosol/450f604fce19b8ae858dd84ace5cc339 to your computer and use it in GitHub Desktop.
parsing paths with vars ~ pcre
<?php
$value = <<<'TXT'
~usrnm/$var/ha${var0}else/this_${var1:-default1}/this_${var2:-default2}_is/*/hi/
~/$this_${var0:-default0}this_${var1:-default1}_is/*/hi/
~us_rnm/$var0/${var1}else/a/this_${var2:-default2}/*/hi
~/ghehe/so/right
/root/file/fs
wrong
/.
../
~\ghehe\so\wrong?
%USERPROFILE%/lol/lol
C:/Program Files/%USERPROFILE%/whatever
C:\Program Files\%USERPROFILE%\whatever
~usrnm/$var/${v${ghe}ar}else/this_${var:-default}/*/hi/
~/ghehe/so/right/
/root/file/fs/
~\ghehe\so\wrong?\
%USERPROFILE%/lol/lol/
C:\Program Files\whatever\
TXT;
$lines = explode( "\n" , $value );
foreach ( $lines as $no => $line )
{
if ( '#' === substr( ltrim( $line , ' ' ) , 0 , 1 ) )
{
continue;
}
$regex = '@
(?: ^ (?P<dirsH> ~ ) (?P<username> [^/\n]+ )? / )
| (?:/)? (?P<dirsC> (?: [^/${}:%\n]*
(?: \${ (?P<vDollarAccollade> [^/${}:%\n]+ ) (?: : (?: - (?<vDefault> [^/${}:%\n]+ ) )? )? } [^/${}:%\n]* )
| (?: (?: \$ (?P<vDollar> [^/${}:%\n]+ ) )
| (?: % (?P<vPercent> [^/${}:%\n]+ ) % ) [^/${}:%\n]*
)
[^/${}:%\n]* ) | (?: [^/${}:%\n]+ )
)
@mx';
preg_match_all( $regex , $line , $match , PREG_UNMATCHED_AS_NULL );
$matches[ $no ][ 'line' ] = $line;
foreach ( $match as $k => $v )
{
if ( is_int( $k ) )
{
continue;
}
$v = array_filter( $v );
if ( 0 === count( $v ) )
{
continue;
}
$matches[ $no ][ $k ] = implode( ' , ' , $v );
}
}
var_dump( $matches );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment