PhP Regex or Basename() - php

I'm trying to extract filenames from a list of files with pathes like :
/a/b/c/d/file1.jpg
/e/f/g/h/file2.png
/i/j/k/l/file3.txt
I want to get a string that is a valid filename (for linux) that is between a "/" is a jpeg file (ends with ".jpg").
In this example, "file1" would be the only valid match.
At the moment I have this RegEx :
/(?<=\/)(.*?)(?=\.(js))/gim
I don't really know if it's better to do this with RegEx or if it's better / possible with basename().
The goal I want to achieve is to get all the strings that match to be placed in an array.
Don't know if I'm doing this right though.

Regex isn't required here. I've assumed you can get your paths into an array.
<?php
$text = file_get_contents("list.txt");
$foo = explode(PHP_EOL, $text);
$bar = array();
foreach($foo as $key => $value){
if(pathinfo($value, PATHINFO_EXTENSION) == "jpg"){
$bar[] = basename($foo[$key],".".pathinfo($value, PATHINFO_EXTENSION));
}
}
print_r($bar);
?>
Outputs:
Array ( [0] => file1 )
Live example: http://codepad.viper-7.com/ewkUHs

Related

How to remove garbage data from array output

I am inserting multiple images on server and storing there name in SQL database by (,) seperated using this.
if($request->hasFile('images')){
$images= [];
foreach($images=$request->file('images') as $img) {
$name=$img->getClientOriginalName();
$img->move(public_path().'/dpic', $name);
$images[]=$name;
}
}
$test =implode(", ", $images);
$product->images =$test;
Image name are inserting into database along with some data it shows output like.
/tmp/php59iuBb, /tmp/phpdRewVH, PicturesI.jpg, Screenshot.png
I want to remove this /tmp/php59iuBb, /tmp/phpdRewVH from output How can I do that.
please guide me to do so.
I would do this
$images =[
'/tmp/php59iuBb', '/tmp/phpdRewVH', 'PicturesI.jpg', 'Screenshot.png'
];
$images = preg_grep('~^(?!/tmp/)~', $images);
print_r($images);
Output
Array
(
[2] => PicturesI.jpg
[3] => Screenshot.png
)
Sandbox
Simple right!
Preg grep runs a regular expression against an array and returns the matches.
In this case
~^(?!/tmp/)~ negative lookbehind - insures that the match does not start with /tmp/
Which leaves us what we want.
Another option is
$images = array_filter($images,function($image){
return substr($image, 0, 5) != '/tmp/';
});
If you are not feeling the Regex love.
Sandbox
PS I love preg_grep its often overlooked for easier to understand but much more lengthy code. Preg Filter is another one of those, which you can use to prefix or suffix an entire array. For example I've used it to prepend paths to an array of filenames etc. For example it's this easy:
$images =[
'/tmp/php59iuBb', '/tmp/phpdRewVH', 'PicturesI.jpg', 'Screenshot.png'
];
print_r(preg_filter('~^(?!/tmp/)~', '/home/images/', $images));
//or you can add a whole image tag, if you want, with a capture group (.+) and backrefrence \1
print_r(preg_filter('~^(?!/tmp/)(.+)~', '<img src="/home/images/\1" />', $images));
Output
Array
(
[2] => /home/images/PicturesI.jpg
[3] => /home/images/Screenshot.png
)
Array
(
[2] => <img src="/home/images/PicturesI.jpg" />
[3] => <img src="/home/images/Screenshot.png" />
)
Sandbox
I thought you may find that "trick" useful as you can remove the bad ones and add a path to the good at the same time. They are worth checking out.
http://php.net/manual/en/function.preg-grep.php
http://php.net/manual/en/function.preg-filter.php
I feel like I should mention the same holds true for matching a file extension, which may also be useful, but I will leave that for another day.
Cheers!
Bit late to the party, but I would personally prefer using pathinfo over regular expressions here, since it's dedicated to file paths:
$images = ['/tmp/php59iuBb', '/tmp/phpdRewVH', 'PicturesI.jpg', 'Screenshot.png'];
$images = array_filter($images, function ($image) {
return pathinfo($image, PATHINFO_DIRNAME) !== '/tmp';
});
print_r($images);
Demo: https://3v4l.org/6F6K8
The foreach loop is statement also storing temp path of image to $images
Change variable name in foreach
$images=$request->file('images') tto $image=>$request->file('images')
I will go with this way, hope this helps you.
$images= [];
if($request->hasFile('images')){
foreach($request->file('images') as $img) {
$name = "some_random_sting";
$extension = $img->getClientOriginalExtension();
$imgName = $name .'.'.$extension;
$img->move(public_path().'/dpic', $imgName);
$images[] = $imgName;
}
}
$test = implode(", ", $images);
$product->images = $test;

substr() PHP not working for array elements

$nomadspage = "http://www.nomads.ncep.noaa.gov/pub/data/nccf/com/gfs/prod/";
$html = file_get_contents($nomadspage);
$count = preg_match_all('/<a href="([^"]+)">[^<]*<\/a>/i', $html, $files);
unset($files[1]); //deletes repeat array from preg_match
$files = $files[0]; //deletes container array from preg_match
foreach ($files as $key => $value) {
if (substr($value, 0, 3) !== "gfs") {
unset($files[$key]);
}
}
var_dump($files);
I have an array with file names from an HTTP directory. I want to filter these files names so that all of the files that don't start with the three letters gfs are deleted from the array. However, for some reason, the substr() function does not work. It does not pull a substring from the file names. Therefore, the if statement does not work. Anybody know why this is happening and how to fix it?
$files[0] contains the strings that match the entire regular expression, so substr($value, 0, 3) is always "<a ". You should set $files to $files[1], not $files[0], it contains all the matches of the ([^"]+) pattern.
Actually, it's best not to use regular expressions to parse HTML. Use a DOM parser library, such as the DOMDocument class.

Get contents from a text file and save its values

I need to get the contents of a text file called file.txt. The contents of that file are:
word1,word 2,word 3 1,another word 1,
I have a config.php which includes:
$file = "file.txt";
$value = explode(",", $file);
And script.php file which will execute other commands based on $value which includes:
if (count(explode($value, $chat))>1) {
After that, it will execute a command if the $value was detected in $chat. So, I need the $value to be a separate word in file.txt.
How can I do this?
If you're looking for more flexibility, you might want to try using preg_split rather than explode, which splits on a regular expression. For example, to split on newlines and commas, you could use this:
$text = file_get_contents('text.txt');
$values = preg_split('/[\n,]+/', $text);
Testing it out:
$s = "word1,word 2\n word 3";
print_r(preg_split('/[\n,]+/', $s));
Output:
Array
(
[0] => word1
[1] => word 2
[2] => word 3
)
Putting that into your script:
$file = "file.txt";
$text = file_get_contents($file);
$values = preg_split('/[\n,]+/', $text);
Then $values is an array, which you can loop over in the other script:
foreach ($values as $value) {
// do whatever you want with each value
echo $value;
}
Reading file contents:
file_get_contents
Explode string:
explode
Get file as array (each line => one item):
file
BTW: a short google would already answer your question...
In config.php add this code, be sure that the file is in the same folder
$value = file_get_contents('file.txt');
Then in script.php add this code:
$pieces = explode(",", $value);
Read more about file_get_contents and explode. (Click on the names)

PHP regex for image name with numbers

I have images with names such as:
img-300x300.jpg
img1-250x270.jpg
These names will be stored in a string variable. My image is in Wordpress so it will be located at e.g.
mywebsite.com/wp-content/uploads/2012/11/img-300x300.jpg
and I need the string to be changed to
mywebsite.com/wp-content/uploads/2012/11/img.jpg
I need a PHP regular expression which would return img.jpg and img1.jpg as the names.
How do I do this?
Thanks
Addition
Sorry guys, I had tried this but it didn't work
$string = 'img-300x300.jpg'
$pattern = '[^0-9\.]-[^0-9\.]';
$replacement = '';
echo preg_replace($pattern, $replacement, $string);
You can do this using PHP native functions itself.
<?php
function genLink($imagelink)
{
$img1 = basename($imagelink);
$img = substr($img1,0,strrpos($img1,'-')).substr($img1,strpos($img1,'.'));
$modifiedlink = substr($imagelink,0,strrpos($imagelink,'/'))."/".$img;
return $modifiedlink;
}
echo genLink('mywebsite.com/wp-content/uploads/2012/11/flower-img-color-300x300.jpg');
OUTPUT :
mywebsite.com/wp-content/uploads/2012/11/flower-img-color.jpg
You can do that as:
(img\d*)-([^.]*)(\..*)
and \1\3 will contain what you want:
Demo: http://regex101.com/r/vU2mD4
Or, replace (img\d*)-([^.]*)(\..*) with \1\3
May be this?
(\w+)-[^.]+?(\.\w+)
The $1$2 will give you what you want.
search : \-[^.]+
replace with : ''
(.[^\-]*)(?:.[^\.]*)\.(.*)
group 1 - name before "-"
group 2 - extension. (everything after ".")
As long as there is only one - and one . then explode() should work great for this:
<?php
// array of image names
$images = array();
$images[] = 'img-300x300.jpg';
$images[] = 'img1-250x270.jpg';
// array to store new image names
$new_names = array();
// loop through images
foreach($images as $v)
{
// explode on dashes
// so we would have something like:
// $explode1[0] = 'img';
// $explode1[1] = '300x300.jpg';
$explode1 = explode('-',$v);
// explode the second piece on the period
// so we have:
// $explode2[0] = '300x300';
// $explode2[1] = 'jpg';
$explode2 = explode('.',$explode1[1]);
// now bring it all together
// this translates to
// img.jpg and img1.jpg
$new_names[] = $explode1[0].'.'.$explode2[1];
}
echo '<pre>'.print_r($new_names, true).'</pre>';
?>
That's an interesting question, and since you are using php, it can be nicely solved with a branch reset (a feature of Perl, PCRE and a few other engines).
Search: img(?|(\d+)-\d{3}x\d{3}|-\d{3}x\d{3})\.jpg
Replace: img\1.jpg
The benefit of this solution, compared with a vague replacement, is that we are sure that we are matching a file whose name matches the format you specified.

Combine two regular expressions into one, matching first and last part of URL?

How can I combine two regexes?
For example, I have this string:
/path/to/file/name.jpg
I want to match two parts of this string with only one regex, so that I can have "/path/to/file/" (everything but last part of url) and "name.jpg". Is it possible?
Edit: I know there are other ways of doing this using PHP functions, but I need to do it with Regex!
if (preg_match('#^(.*?/)([^/]+)$#', $path, $matches))
{
list($all, $directory, $filename) = $matches;
}
Even though there are specific functions like pathinfo() dirname() and basename()
Use pathinfo():
$foo = '/path/to/file/name.jpg';
$bits = pathinfo($foo);
print_r($bits);
That will give you:
Array
(
[dirname] => /path/to/file
[basename] => name.jpg
[extension] => jpg
[filename] => name
)
Sure it is possible:
/^(?P<path>.*?)(?P<filename>[^\/]*)$/
phpfiddle example
In this special case I would not use a regex at all. Use:
$path = dirname('/path/to/file/name.jpg'); // /path/to/file
$filename = basename('/path/to/file/name.jpg'); // name.jpg
If you need a regex, use something like this:
$str = 'path/to/file/name.jpg';
$pattern = '~(.*)(/.*)~';
preg_match($pattern, $str, $matches);
$path = $matches[1];
$filename = $matches[2];

Categories