Removing the .htm From Items in a PHP Array
How can I remove the .htm from the end of each of the items in an array? I'm very new to PHP, so as specific help as possible would be greatly appreciated.
Here's my script:
<?PHP
$myDirectory = opendir("pages/");
while($entryName = readdir($myDirectory)) {
$dirArray[] = $entryName;
}
closedir($myDirectory);
$indexCount = count($dirArray);
sort($dirArray);
for($index=0; $index < $indexCount; $index++) {
if (substr("$dirArray[$index]", 0, 1) != "."){ // don't list hidden files
print("<a href=\"index.php?p=$dirArray[$index]\"&g开发者_如何学Got;$dirArray[$index]</a>/n");
}
}
?>
Assuming that the string is not guaranteed to always have .htm
at the end, running the string you want to modify through the following function should work for you:
$str = preg_replace('/\.htm$/', '', $str);
You could use array_map()
(to iterate over the array) and pathinfo()
(to return just the filename portion minus the extension).
This will work with any filename extension.
$dirArray = array_map(function($item) {
return pathinfo($item, PATHINFO_FILENAME);
}, $dirArray);
CodePad.
The anonymous function is a >= PHP 5.3 thing. Just use a named function if using an older version.
You can simplify your code with iterators. Here's an example:
foreach (new DirectoryIterator('pages') as $fileInfo) {
if ($fileInfo->isFile()) {
$name = $fileInfo->getBasename('.htm');
print("<a href='index.php?p=$name'>$name</a><br>");
}
}
精彩评论