Is there an easier way to crop a string with a PHP regular expression?

I have a line that looks like this:

Security/Flow_Setup/Steady_State/Verification

I need only the first two levels (for example, Security / Flow _Setup ). Is there an easier way to get this. I am currently inserting a string into an array using: '/' as a separator, and then concatenating elements 0 and 1.

This works, but I was hoping for a more elegant solution.

Any thoughts?

+3
source share
5 answers

I don't think you can get too elegant / short than this if you only need the first two parts:

list($var1, $var2) = explode('/', $str);

Regex is completely unnecessary here.

- dirname , , , , ( , ):

$str = 'Security/Flow_Setup/Steady_State/Verification';

echo dirname(dirname($str));

// Output: Security/Flow_Setup
+7

, . , :

$str = "Security/Flow_Setup/Steady_State/Verification";
echo substr($str, 0, strpos($str, '/', strpos($str, '/') + 1));

( , )

+3

not a typical use or string function, but since your string is an efficient way, maybe this will be enough ...

dirname(dirname('Security/Flow_Setup/Steady_State/Verification'));
+2
source

Here is the shortest and most efficient single line drawer I can think of:

$firstTwoParts = implode('/', array_slice(explode('/', $str, 3), 0, 2));

This can be wrapped in a function that allows you to control how many parts you want:

function first_n_parts ($str, $n, $delimiter = '/') {
  return ($n = (int) $n) ? implode($delimiter, array_slice(explode($delimiter, $str, $n + 1), 0, $n)) : '';
}

... so you can do:

echo first_n_parts($str, 1); // Security
echo first_n_parts($str, 2); // Security/Flow_Setup
echo first_n_parts($str, 3); // Security/Flow_Setup/Steady_State
+1
source

this regex should do it

'/^([a-zA-Z]+\/[a-zA-Z]+)?/'
0
source

All Articles