dousa1630 2014-03-31 14:43
浏览 233
已采纳

通过使用正则表达式查看别名来获取“使用”命名空间

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?

  • 写回答

2条回答 默认 最新

  • doulou9927 2014-03-31 16:54
    关注

    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 "
    ".$pattern.": ".$matches[0];
    
    }
    

    This outputs:

    Name1: Foo\Bar\Baz
    Name2: Foo\Bar\Qux
    Name3: Foo\Bar\Corge
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 有人能看一下我宿舍管理系统的报修功能该怎么改啊?链表那里总是越界
  • ¥15 cs loadimage运行不了,easyx也下了,没有用
  • ¥15 r包runway详细安装教程
  • ¥15 Html中读取Json文件中数据并制作表格
  • ¥15 谁有RH342练习环境
  • ¥15 STM32F407 DMA中断问题
  • ¥15 uniapp连接阿里云无法发布消息和订阅
  • ¥25 麦当劳点餐系统代码纠错
  • ¥15 轮班监督委员会问题。
  • ¥20 关于变压器的具体案例分析