Areku_UA
Areku_UA

Reputation: 311

PHP Regexp on filename and number

How to catch and filer the filename

Input:

news.jpg
news_1.png
asnews_2.gif
asnews_3.jpeg
aw_news_4.jpg
aw_news.gif

Outout:

Array
(
[0] => Array
    (
        [0] => news
        [1] => news_1
        [2] => asnews_2
        [3] => asnews_3
        [4] => aw_news_4
        [5] => aw_news
    )

[1] => Array
    (
        [0] => 
        [1] => 1
        [2] => 2
        [3] => 3
        [4] => 4
        [5] => 
    )

[2] => Array
    (
        [0] => news
        [1] => news
        [2] => asnews
        [3] => asnews
        [4] => aw_news
        [5] => aw_news
    )

)

I have tried in PHP using preg_match_all and preg_replace_callback, which I dont how to use correctly.

preg_match_all('/(?: _???_ (?:_([\d]+))?$/im', $fullname, $result);  // $fullname - string

This is a similar example - /(?:(?:_([\d]+))?(.[^.]+))$/. You can change this.

Upvotes: 1

Views: 60

Answers (3)

Mikhail Vladimirov
Mikhail Vladimirov

Reputation: 13890

$result = array (array (), array (), array ());

$dir = opendir ("/tmp");
while (($file = readdir ($dir)) !== false)
{
  if ($file == '.' || $file == '..') continue;

  $matches = array ();
  preg_match ('/^(([^.]*?)(?:_([0-9]*))?)(?:\.|$)/', $file, $matches);

  $result [0][] = $matches [1];
  $result [1][] = $matches [3];
  $result [2][] = $matches [2];
}
closedir ($dir);

print_r ($result);

Output is:

Array
(
    [0] => Array
    (
        [0] => news
        [1] => news_1
        [2] => asnews_2
        [3] => asnews_3
        [4] => aw_news_4
        [5] => aw_news
    )

    [1] => Array
    (
        [0] =>
        [1] => 1
        [2] => 2
        [3] => 3
        [4] => 4
        [5] =>
    )

    [2] => Array
    (
        [0] => news
        [1] => news
        [2] => asnews
        [3] => asnews
        [4] => aw_news
        [5] => aw_news
    )
)

Upvotes: 2

웃웃웃웃웃
웃웃웃웃웃

Reputation: 11984

Try explode function in php.Explode the string contains filename.Use '.' as the explode delimeter and extraxt the exploded array to get the file name.

For reference about explode manual try this

http://php.net/manual/en/function.explode.php

Upvotes: 0

silkfire
silkfire

Reputation: 25945

Use the basename() function to retrieve the file name without its extension.

  • basename() — Returns filename component of path

Upvotes: 0

Related Questions