Page 1 of 1
[SOLVED]editing array elements
Posted: Tue May 24, 2005 1:11 pm
by rubberjohn
i have an array where all the values are the names of text files. what is the best way to take out each value, remove the .txt extension and then place the resulting filename back into an array in the same order as the original array?
thanks in advance
Posted: Tue May 24, 2005 1:18 pm
by shiznatix
off the top of my head, might not be the best way but would certainly work
Code: Select all
foreach ($array as $key => $value)
{
$array[$key] = str_replace('.txt', '', $value);
}
Posted: Tue May 24, 2005 1:31 pm
by Skara
And what if a file is named "something.txtfile.txt" ?
Use this instead:
Code: Select all
foreach ($array as $key => $value) {
$array[$key] = preg_replace('/^(.+)\.txt$/i', '\\1', $value);
}
Posted: Tue May 24, 2005 1:32 pm
by shiznatix
off topic a lil but which is faster, str or preg
Posted: Tue May 24, 2005 1:43 pm
by Skara
hm. Dunno. *googles*
Don't know if it's true (though it is likely), phpfreaks had this post:
preg is much faster than ereg. the str* functions of php are probably around 10 x faster than regex
back to the original q for a sec
Posted: Tue May 24, 2005 1:57 pm
by rubberjohn
ok ive tried this
Code: Select all
foreach ($temp as $key => $value){
$temp[$key] = str_replace('.txt', '', $value);
print_r($value);
}
and this is what i get
Code: Select all
Array ( ї0] => greengame.txt ї1] => smalltable.txt ї2] => notes.txt ї3] => fishdrawn.txt ї4] => pattern.txt ї5] => girl.txt ї6] => net.txt ї7] => peddle.txt ї8] => table.txt ї9] => cross.txt ї10] => paving.txt ї11] => woodslice.txt ї12] => underwater.txt ї13] => yellowtap.txt ї14] => wood.txt ї15] => paint3.txt ї16] => coffee.txt ї17] => bath.txt ї18] => lacetable.txt ї19] => mosaic.txt ї20] => clock.txt )
what am i doing wrong? i dont think ive got the hang of 'foreach' yet
Posted: Tue May 24, 2005 1:58 pm
by shiznatix
print_r after you get out of the foreach
Code: Select all
foreach ($temp as $key => $value)
{
$temp[$key] = str_replace('.txt', '', $value);
}
print_r($temp);

same same
Posted: Tue May 24, 2005 2:05 pm
by rubberjohn
just tried that and the result is still the same and i tried the other way aswell
Posted: Tue May 24, 2005 2:15 pm
by shiznatix
huh after some testing for some reason you need to just remove the . from .txt in the str replace fucntion
str_replace('txt', '', $value);
is what is should look like, i have no idea why the . messes it up, i even tried escaping it with a \.txt but that didnt work, theres your solution, just remove the . from the str replace but if anyone knows why this is the case then please tell me
thanks
Posted: Tue May 24, 2005 2:20 pm
by rubberjohn
cheers shiznatix thats done the trick, i can finally get this finished now
Posted: Tue May 24, 2005 2:29 pm
by shiznatix
that will be 13401873982365 us dollars please
