23

This is a custom function. At the moment, this function get all the file in the default directory, strip ".php" and list them.

The problem is that I want to only get files from the directory which has starting prefix "tpl-" Example : tpl-login-page.php

/* Get template name of the file */
        function get_template_name (){
            $files = preg_grep('~\.(php)$~', scandir(admin . "templates/default/"));
                foreach($files as $file){
                    $file = str_replace('.php','',$file);
                    echo $file . "<br/>";
                }
        }
1
  • So you're probably looking to modify the preg_grep expression ~\.(php)$~. Commented Dec 7, 2013 at 4:37

3 Answers 3

28

You need to change the regular expression in preg_grep:

$files = preg_grep('~^tpl-.*\.php$~', scandir(admin . "templates/default/"));

Explanation:

  1. ^tpl- - starting with "tpl-"

  2. .* - any characters

  3. \.php$ - ending with ".php"

Sign up to request clarification or add additional context in comments.

Comments

24

I like another, simple way:

1. get all files in folder

   $path = './images'; 
   $files = glob($path.'/*');

2. get all files having extension .jpg

   $path = './images'; 
   $files = glob($path.'/*.jpg');

3. get all files having prefix myprefix_

   $path = './images'; 
   $files = glob($path.'/myprefix_*');

Comments

1
 $target_file_png = glob($target_dir.'/group_'.$groupId.'*.png'); 

$target_file_png will return an array containing all the files in folder specified in the path $target_dir starting with '/group_'.$groupId.' and specify the file format as *.png

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.