0

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!

4
  • 1
    Why not explode('\\', $nameSpace);? Commented Mar 10, 2014 at 21:06
  • @RocketHazmat Explode is slow, I had my issues before with it, even my current solution based on substr() goes faster, but I would like do it regex-based. Thank you! Commented Mar 10, 2014 at 21:09
  • Is this for an autoloader? Commented Mar 10, 2014 at 21:22
  • @WesleyMurch nop, it's for a personal ORM-like thing. Commented Mar 10, 2014 at 21:31

3 Answers 3

1

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
Sign up to request clarification or add additional context in comments.

Comments

1

I think maybe preg_match might be a better choice for this.

$s = '\\Base\\Ent\\User';
$m = [];
print preg_match('/([^\\\\]*)\\\\[^\\\\]*$/', $s, $m);
print $m[1];

If you read the regular expression backwards, from the $, it says to match many things that aren't backslashes, then a backslash, then many things that aren't backslashes, and save that match for later (in $m).

Comments

0

How about

$path = '\Base\Ent\User';
$section = substr(strrchr(substr(strrchr($path, "\\"), 1), "\\"), 1);

Or

$path = '\Base\Ent\User';
$section = strstr(substr($path, strpos($path, "\\", 1)), "\\", true);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.