dongnaoben4456 2014-03-10 21:05
浏览 42
已采纳

PHP:preg_replace()获取NameSpace的“父”组件

How can I use the preg_replace() replace function to only return the parent "component" of a PHP NameSpace?

Basically:

Input: \Base\Ent\User; Desired Output: Ent

I've been doing this using substr() but I want to convert it to regex. Note: Can this be done without preg_match_all()?

Right now, I also have a code to get all parent components:

$s = '\\Base\\Ent\\User';
print preg_replace('~\\\\[^\\\\]*$~', '', $s);
//=> \Base\Ent

But I only want to return Ent.

Thank you!

  • 写回答

3条回答 默认 最新

  • dongyi8795 2014-03-10 21:27
    关注

    As Rocket Hazmat says, explode is almost certainly going to be better here than a regex. I would be surprised if it's actually slower than a regex.

    But, since you asked, here's a regex solution:

    $path = '\Base\Ent\User';
    $search = preg_match('~([^\\\\]+)\\\\[^\\\\]+$~', $path, $matches);
    if($search) {
        $parent = $matches[1];
    }
    else {
        $parent = ''; // handles the case where the path is just, e.g., "User"
    }
    echo $parent; // echos Ent
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 单片机学习顺序问题!!
  • ¥15 ikuai客户端多拨vpn,重启总是有个别重拨不上
  • ¥20 关于#anlogic#sdram#的问题,如何解决?(关键词-performance)
  • ¥15 相敏解调 matlab
  • ¥15 求lingo代码和思路
  • ¥15 公交车和无人机协同运输
  • ¥15 stm32代码移植没反应
  • ¥15 matlab基于pde算法图像修复,为什么只能对示例图像有效
  • ¥100 连续两帧图像高速减法
  • ¥15 如何绘制动力学系统的相图