Domanda

Suppose I have PHP code in a string variable. In that PHP code I have namespaces where some have an alias. I'd like to get the full namespace with regex by using the alias.

So for example, suppose I have the following code in a variable:

<?php
namespace Something;

use Foo\Bar\Baz as Name1, Foo\Bar\Qux as Name2;
use Foo\Bar\Grault, 
Foo\Bar\Quux;
use Foo\Bar\Corge as Name3;

class Test {
    // Class code ommited in this example
}
?>

I know the alias Name1 is in the code. So i'd like to get the full namespace from that alias.

So in this case I'd like to get the following string back when I search for Name1:

[0] => Foo\Bar\Baz

And in the case of Name3 I'd like to see:

[0] => Foo\Bar\Corge

The same should apply when I try to look forany other alias. Also, please note that sometimes that namespaces are separated by a comma and sometimes a newline occurs. The regex should be able to handle this.

I have the following so far, but it's not working the way I'd like. Especially when I search for Name3.

preg_match ( '~use(.*?)as +'.$alias.'(,|;)~s', $source, $matches )

Demo: http://codepad.viper-7.com/a9GtTH

Anyone any idea how I could get the desired result?

È stato utile?

Soluzione

Here's something you can try:

$string = 'namespace Something;

use Foo\Bar\Baz as Name1, Foo\Bar\Qux as Name2;
use Foo\Bar\Grault, 
Foo\Bar\Quux;
use Foo\Bar\Corge as Name3;';

$array_of_patterns = array('Name1', 'Name2', 'Name3');

foreach ($array_of_patterns AS $pattern) {

    preg_match('~\b([A-Z\\\]+)(?= as '.$pattern.')~i', $string, $matches);
    print "\n".$pattern.": ".$matches[0];

}

This outputs:

Name1: Foo\Bar\Baz
Name2: Foo\Bar\Qux
Name3: Foo\Bar\Corge

Altri suggerimenti

This works for Name1 and Name3, it doesn't handle names after a comma...:

<?php

  $source = "
    <?php

      namespace Something;

      use Foo\Bar\Baz as Name1, Foo\Bar\Qux as Name2;
      use Foo\Bar\Grault,
      Foo\Bar\Quux;
      use Foo\Bar\Corge as Name3;

      class Test {
          // Class code ommited in this example
      }
    ?>
  ";

  $alias = 'Name1'; # 'Name1' / 'Name2' / 'Name3'
  preg_match('/use\s+(.*?)\s+as\s+'.$alias.'\s*[,;].*/', $source, $matches);
  print $matches[1];
?>
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top