php - Split foreach results into reusable variables -


i have foreach function:

foreach ($result $result) {   echo "<a href='" . $result . "'>" . $result . "</a><br>"; } 

which generates list this:

[spacer]_[timespacer]_fiveseconds.wav [trudy]_[0x06ddd12a]_i.wav [trudy]_[0x06ddd12a]_get.wav [spacer]_[timespacer]_halfsecond.wav [spacer]_[timespacer]_onesecond.wav 

i tried explode & split function returns whole list of:

array array 

what want achieve have foreach $result variable holds word/name in between first set of [] , variable holds second set of [] third variable holds between last _ , .wav. have these variables:

$result_classname = spacer $result_parent = timespacer $result_name = fiveseconds $result = [spacer]_[timespacer]_fiveseconds.wav 

which allow me do:

foreach ($result $result) {   echo "<a class='" . $result_classname . "' href='" . $result . "'>" . $result_name . "</a><span>" . $result_parent . "</span><br>"; } 

how can achieve this?

first, don't want use same variable in foreach:

foreach ($result $result) { 

use different variable:

foreach ($result $value) { 

then, here non regex way handle this:

list($classname, $parent, $name) = explode('_', $value); $classname = trim($classname, '[]'); $parent    = trim($parent, '[]'); $name      = pathinfo($name, pathinfo_filename); 
  • explode on underscores
  • trim [] characters each end
  • get filename without extenstion

or simple regex:

preg_match('/\[([^\]]+)\]_\[([^\]]+)\]_([^.]+).*/', $value, $matches); 

then use print_r($matches); see ones use ($matches[0], etc.).


Comments