Skip to content

Instantly share code, notes, and snippets.

@saxenap
Last active November 17, 2015 20:17
Show Gist options
  • Save saxenap/15193a9a7ff01619f8c2 to your computer and use it in GitHub Desktop.
Save saxenap/15193a9a7ff01619f8c2 to your computer and use it in GitHub Desktop.
Extracts declared namespaced and/or aliased classes from a class file using regex.
$searchForDeclaration
= new WordBoundaryAround(
new OptionalSpacesAround(
new Group(
new Alteration(['use', ',']))));
$matchNamedSpace
= new Optional(
new NamedGroup(
'namespace',
new ValidNamespace)
. new NamespaceSeparator);
$matchClassName = new NamedGroup('classname', new ValidClassName);
$matchAlias =
new Optional(
new SpacesAround('as')
. new NamedGroup('alias', new ValidClassName));
$options = new CaseInsensitiveMatch . new MultiLineMatch;
$regex =
'~'
. $searchForDeclaration
. $matchNamedSpace
. $matchClassName
. $matchAlias
. '~'
. $options
;
$matches = [];
preg_match_all($regex, $fileContents, $matches, PREG_SET_ORDER);
// The regex created above is :
//$regex = '~\b(?:\s)?+(use|,)(?:\s)?+\b(?:(?P<namespace>[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*(?:(\x5c[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*)*)?)\x5c)?(?P<classname>[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*)(?:\s+as\s+(?P<alias>[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*))?~im';
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment