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;
Related
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.
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];
I've been trying to use preg_match_all for 30 minutes but it looks like I can't do it.
Basically I have a $var which contains a string of HTML code. For example:
<br>iihfuhuf
<img title="Image: http://www.jlnv2.local/temp/temp513caca536fcd.jpeg"
src="http://www.jlnv2.local/temp/temp513caca536fcd.jpeg">
<img src="http://www.jlnv2.local/temp/temp513caca73b8da.jpeg"><br>
I want to get the src attribute values of img tags that contain /temp/temp[a-z0-9]{13}\.jpeg in their src value.
This is what I have so far:
preg_match_all('!(<img.*src=".*/temp/temp[a-z0-9]{13}\.jpeg"(.*alt=".*")?>)!', $content, $matches);
<img[^>]*src="([^"]*/temp/temp[a-z0-9]{13}\.jpeg)"
<img[^>]* Select IMG tags
src="([^"]*)" gets src value and save it as a match
/temp/temp[a-z0-9]{13}\.jpeg is the filter for src values
For quick RegEx tests use some online tool like http://regexpal.com/
All you need to do is add another group to your regular expression. You have du surround everything you want to extract from the match with braces:
preg_match_all('!(<img.*src="(.*/temp/temp[a-z0-9]{13}\.jpeg)"(.*alt=".*")?>)!', $content, $matches);
You can see that working here. You can find the URLs in $matches[2].
But just for having said it: Regular expressions are no reasonable approach to extract anything from HTML. You would be better off using DOMDocument, XPath or something along that line.
Try this:
preg_match_all('/src="([^"]+temp[a-z0-9]{13}\.jpeg)"/',$url,$matches);
var_dump($matches);
<?php
$text = '<br>iihfuhuf<img title="Image: http://www.jlnv2.local/temp/temp513caca536fcd.jpeg" src="http://www.jlnv2.local/temp/temp513caca536fcd.jpeg"><img src="http://www.jlnv2.local/temp/temp513caca73b8da.jpeg"><br>';
$pattern = '#src="([^"]+/temp/temp[a-z0-9]{13}\.jpeg)"#';
preg_match_all($pattern, $text, $out);
echo '<pre>';
print_r($out);
?>
Array
(
[0] => Array
(
[0] => src="http://www.jlnv2.local/temp/temp513caca536fcd.jpeg"
[1] => src="http://www.jlnv2.local/temp/temp513caca73b8da.jpeg"
)
[1] => Array
(
[0] => http://www.jlnv2.local/temp/temp513caca536fcd.jpeg
[1] => http://www.jlnv2.local/temp/temp513caca73b8da.jpeg
)
)
Here is a DOMDocument/DOMXPath based example of how to do it. This is arguably the only right way to do it, because unless you are really good at regular expressions there will most likely always be edge cases that will break your logic.
$doc = new DOMDocument;
$xpath = new DOMXPath($doc);
$doc->loadHTML($content);
$candidates = $xpath->query("//img[contains(#src, '/temp/temp')]");
$result = array();
foreach ($candidates as $image) {
$src = $image->getAttribute('src');
if (preg_match('/temp[0-9a-z]{13}\.jpeg$/', $src, $matches)) {
$result[] = $src;
}
}
print_r($result);
$text = '<br>iihfuhuf<img title="Image: http://www.jlnv2.local/temp/temp513caca536fcd.jpeg" src="http://www.jlnv2.local/temp/temp513caca536fcd.jpeg"><img src="http://www.jlnv2.local/temp/temp513caca73b8da.jpeg"><br>';
$pattern = '#src="([^"]+/temp/temp[a-z0-9]{13}\.jpeg)"#';
preg_match( '#src="([^"]+)"#' , $text, $match );
$src = array_pop($match);
echo $src;
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
what is the best way of extracting multiple (~40 values) from a text file using php?
the data is more or less like:
NAMEA valuea
NAMEB valueb
I'm looking for a proper* approach to extracting this data into a data-structure, because i will need to specify regexs for all of them (all 40).
did i make myself clear?
*meaning, the default/painful method would be for me to do:
$namea = extractfunction("regexa", $textfilevalue);
$nameb = extractfunction("regeb", $textfilevalue);
... 40 times!
The lines may not be in the same order, or be present in each file. Every NAMEA is text like: "Registration Number:", or "Applicant Name:" (ie, with spaces in what i was calling as NAMEA)
Response to the Col.
i'm looking for a sensible "way" of writing my code, so its readable, modifiable, builds an object/array thats easily callable, etc... "good coding style!" :)
#Adam - They do actually... and contain slashes as well...
#Alix - Freaking marvelous man! THat was GOOD! would you also happen to have any insights on how I can "truncate" the rsultant array by removing everything from "key_x" and beyond? Should i open that as a new question?
Here is my take at it:
somefile.txt:
NAMEA valuea
NAMEB valueb
PHP Code:
$file = file_get_contents('./somefile.txt');
$string = preg_replace('~^(.+?)\s+(.+?)$~m', '$1=$2', $file);
$string = str_replace(array("\r\n", "\r", "\n"), '&', $string);
$result = array();
parse_str($string, $result);
echo '<pre>';
print_r($result);
echo '</pre>';
Output:
Array
(
[NAMEA] => valuea
[NAMEB] => valueb
)
You may also be able to further simplify this by using str_getcsv() on PHP 5.3+.
EDIT: My previous version fails for keys that have spaces like #Col. Shrapnel noticed. I didn't read the question with enough attention. A possible solution since you seem to be using keys that always have : appended is this:
$string = preg_replace('~^(.+?):\s+(.+?)$~m', '$1=$2', $file);
To remove everything from key_x to the end of the file you can do something like this:
$string = substr($string, 0, strpos($string, 'key_x'));
So the whole thing would look like this:
somefile.txt:
Registration Number: valuea
Applicant Name: valueb
PHP Code:
$file = file_get_contents('./somefile.txt');
$string = substr($file, 0, strpos($file, 'key_x'));
$string = preg_replace('~^(.+?):\s+(.+?)$~m', '$1=$2', $string);
$string = str_replace(array("\r\n", "\r", "\n"), '&', $string);
$result = array();
parse_str($string, $result);
echo '<pre>';
print_r($result);
echo '</pre>';
Output:
Array
(
[Registration_Number] => valuea
[Applicant_Name] => valueb
)
as far as I get it you can use file() to get an array of strings and then parse these strings with some regexp.
if you add a = sign between names and values, you'll be ble to get the whole thing at once using parse_ini_file()
Assuming your keys (namea, nameb) never have spaces in them:
$contents = file('some_file.txt'); // read file as array
$data = array();
foreach($contents as $line) { // iterate over file
preg_match('/^([^\s]+)\s+(.*)/', $line, $matches); // pull out key and value into $matches
$key = $matches[1];
$value = $matches[2];
$data[$key] = $value; // store key/value pairs in $data array
}
var_dump($data); // what did we get?