hy I want grab every filename for example :
I have data
01.jpg02.jpg03.jpg10599335_899600036724556_4656814811345726851_n.jpg11693824_1051832718167953_6310308040295800037_n.jpg11709788_1051835281501030_8503525152567309473_n.jpg12042832_1103685106316047_3711793359145824637_n.jpg
I'm try like this but not working for me
$str = $_POST['name'];
print_r (explode(".jpg", $str));
foreach ($str as $key => $value) {
echo $value.'<br>';
}
The solution using preg_match_all
function:
$str = "01.jpg02.jpg03.jpg10599335_899600036724556_4656814811345726851_n.jpg11693824_1051832718167953_6310308040295800037_n.jpg11709788_1051835281501030_8503525152567309473_n.jpg12042832_1103685106316047_3711793359145824637_n.jpg";
preg_match_all("/(?<=\.jpg)?\w+\.jpg/", $str, $matches);
print_r($matches[0]);
The output:
Array
(
[0] => 01.jpg
[1] => 02.jpg
[2] => 03.jpg
[3] => 10599335_899600036724556_4656814811345726851_n.jpg
[4] => 11693824_1051832718167953_6310308040295800037_n.jpg
[5] => 11709788_1051835281501030_8503525152567309473_n.jpg
[6] => 12042832_1103685106316047_3711793359145824637_n.jpg
)
You can use this lookbehind regex in preg_match_all
:
/(?<=^|\.jpg)\w+\.jpg/
Lookbehind asserts that our match has a preceding .jpg
or line start.
Code:
$re = '/(?<=^|\.jpg)\w+\.jpg/m';
preg_match_all($re, $input, $matches);
print_r($matches[0]);
The explode takes the delimited value off so you would need to re-append it.
$filenames = explode('.jpg', '01.jpg02.jpg03.jpg10599335_899600036724556_4656814811345726851_n.jpg11693824_1051832718167953_6310308040295800037_n.jpg11709788_1051835281501030_8503525152567309473_n.jpg12042832_1103685106316047_3711793359145824637_n.jpg');
foreach($filenames as $file) {
if(!empty($file)) {
echo $file . ".jpg
";
}
}
A regex approach that I think would work is:
(.*?\.jpg)
Regex demo: https://regex101.com/r/gR7rC5/1
PHP:
preg_match_all('/(.*?\.jpg)/', '01.jpg02.jpg03.jpg10599335_899600036724556_4656814811345726851_n.jpg11693824_1051832718167953_6310308040295800037_n.jpg11709788_1051835281501030_8503525152567309473_n.jpg12042832_1103685106316047_3711793359145824637_n.jpg', $filenames);
foreach($filenames[1] as $file) {
echo $file . "
";
}
Demo: https://eval.in/596530
preg_match_all("/(.*?\.jpg)/", $str, $out);
Var_dump($out[1]);
Click preg_match_all
http://www.phpliveregex.com/p/gcR