我进行了搜索和搜索。我找不到解决方案。我有一个像这样的字符串:ABC_test 001-2.jpg
我也有这段代码:
$makeSpace = preg_replace("/[^a-zA-Z0-9\s]/", " ", $replaceUnder);
但是,这段代码不会替换下划线(_)。实际上,这个变量的输出是:ABC
一旦它击中下划线就会停止。我需要替换每个可能的非字母数字字符,包括下划线,星号,问号等等。我错过了什么?
感谢您的帮助。
编辑:
<?php
//set images directory
$directory = 'ui/images/customFabrication/';
try {
// create slideshow div to be manipulated by the above jquery function
echo "<div class=\"slideLeft\"></div>";
echo "<div class=\"sliderWindow\">";
echo "<ul id=\"slider\">";
//iterate through the directory, get images, set the path and echo them in img tags.
foreach ( new DirectoryIterator($directory) as $item ) {
if ($item->isFile()) {
$path = $directory . "" . $item;
$class = substr($item, 0,-4); //removes file type from file name
//$replaceUnder = str_replace("_", "-", $class);
$makeDash = str_replace(" ", "-", $replaceUnder);
$replaceUnder = preg_replace("/[^a-zA-Z0-9\s]/", " ", $class);
//$makeSpace = preg_replace("/[^a-zA-Z0-9\s]/", " ", $replaceUnder);
echo "<li><img rel=" . $replaceUnder . " class=" . $class . " src=\"/ui/js/timthumb.php?src=/" . $path . "&h=180&w=230&zc=1\" /></li>";
}
}
echo "</ul>";
echo "</div>";
echo "<div class=\"slideRight\"></div>";
}
//if directory is empty throw an exception.
catch(Exception $exc) {
echo 'the directory you chose seems to be empty';
}
?>
答案 0 :(得分:4)
我无法重现你的问题,对我来说输出的字符串是:
$replaceUnder = 'ABC_test 001-2.jpg';
$makeSpace = preg_replace("/[^a-zA-Z0-9\s]/", " ", $replaceUnder);
print_r($makeSpace);
# output:
# ABC test 001 2 jpg
我浏览了你粘贴的代码并发现了一些错误,这些错误可能是相关的,也许不是:
我在这一行收到错误,因为未定义replaceUnder:
$makeDash = str_replace(" ", "-", $replaceUnder);
因为你评论了这一行:
//$replaceUnder = str_replace("_", "-", $class);
我猜你也打算将它评论出来。目前还不清楚你想要做什么以及为什么你有所有那些替换语句。如果你只是试图用所有替换的符号来回显文件名,这就是我做的方式,所有字母都用空格代替:
<?php
//set images directory
$directory = './';
try {
foreach ( new DirectoryIterator($directory) as $item ) {
if ($item->isFile()) {
$path = $directory . "" . $item;
// remove ending/filetype - the other method doesn't support 4 letter file endings
$name = basename($item);
$fixedName = preg_replace("/[^a-zA-Z0-9\s]/", " ", $name);
echo "Name: $fixedName\n";
}
}
}
//if directory is empty throw an exception.
catch(Exception $exc) {
echo 'the directory you chose seems to be empty';
}
?>
我认为你的整个问题源于变量的命名。考虑启用通知错误 - 如果您引用未定义的变量,它们会通知您。