Search code examples
phpphp-5.4

regexp or strcmp to take some word in string


I'm pretty new in php and come here from C++ so there is no stl library with their strings and so on.

I'm looking for explodes and implodes, want to realize such a check like i have relative path or file name, and want to check is it contains some word, for example '-thumb' before extension or as last entry. Then just store two variables, with that postfix and without. The abstract directory contains two files: test_file.png, test_file-thumb.png, since directory traversing function will pass as file name both of them, or one of them, I want to make sure is main file in there, after all checks complete i call StoreBothFiles method like that:

// this variables will comes from traverse function:
$file_name = __DIR__ ."test_file.png";
$postfix = "-thumb";

// explode will get name without extension add postfix and add extension
if ( is_file(file_name) && strpbrk($file_name, '-') == FALSE ) {
   $name_noext = explode('.',$file_name, 2); 
   $file_thumb = $name_noext[0] . $postfix . "." . $photo_file_name_noext[1];
   StoreBothFiles($file_name, is_file(file_thumb) ? $file_thumb : null);
}

But it works for all files that have '-' in names and this approach not adapted for absolute paths, I do refactoring and curious, maybe there can be more effictent way to write it in short manner using some regexps or something like that, without messing with substr and strlen with while cycles?


Solution

  • In PHP, string functions are generally preferred over regular expressions for tasks as simple as this.

    $image = 'myimage.jpg';
    
    $ext = pathinfo($image, PATHINFO_EXTENSION); // jpg
    $fname = pathinfo($image, PATHINFO_FILENAME); // myimage
    $thumb = $fname . '-thumb.' . $ext; // myimage-thumb.jpg
    
    echo substr(pathinfo($thumb, PATHINFO_FILENAME), -6, 6); // -thumb