How to do a regex to take from bar (/) to _, ie I just want the digits before _

Asked

Viewed 176 times

1

/dir/user/Desktop/zip/1_0.zip

/dir/user/Desktop/zip/2_0.zip

I want to capture only the numbers in bold. I am doing the following and sending to a foreach but it’s not capturing right:

preg_match_all('/\/(0-9,_)\//', $data);

1 answer

2


In the simplest case (there is only one occurrence of numbers in each string), you could do:

$data = <<<DATA
/dir/user/Desktop/zip/1_0.zip
/dir/user/Desktop/zip/2_0.zip
DATA;

if (preg_match_all('/\/(\d+)_/', $data, $matches)) {
    foreach ($matches[1] as $m) {
        echo $m.PHP_EOL;
    }
}

regex considers a bar (\/), afterward one or more digits (\d+) and the character _.

The digits are in parentheses to form a catch group, so they are all available at position 1 of the array pouch (is the first pair of parentheses of regex, so it is the first capture group, and so they are at position 1). The output is:

1
2

If you have other numbers in the string (for example, /dir/user/3_Desktop/zip/1_0.zip) and you just want to get the last of each string, just make the regex more specific:

if (preg_match_all('/\/(\d+)_[^\/]*zip/', $data, $matches)) {
    ....

In case, I added [^\/]*zip:

  • zero or more characters other than the bar ([^\/]*)
  • the string zip

So if the string is /dir/user/3_Desktop/zip/1_0.zip, he ignores the number 3 and only takes the 1.


His regex had 0-9,_, which is literally "the number zero, followed by a hyphen, followed by the number 9, comma and _". Use 0-9 as interval only works in character classes (in square brackets): [0-9].


If the format is always as specified, another option (without regex) is simply "blow up all":

$partes = explode('/', '/dir/user/Desktop/zip/1_0.zip');
$valor = explode('_', end($partes))[0];
echo $valor; // 1

In case, I break the string using the bar as delimiter, and catch the last part with end. Then break again, using _ as delimiter and take the first part, which corresponds to the number.

Another option is:

$partes = explode('/', '/dir/user/Desktop/zip/1_0.zip');
$ultima = array_values(array_slice($partes, -1))[0];
$valor = explode('_', $ultima)[0];
echo $valor; // 1
  • 1

    Very good explanation, thanks for the help!!!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.