gpt4 book ai didi

PHP用空格替换每个非字母数字字符

转载 作者:可可西里 更新时间:2023-10-31 23:10:49 24 4
gpt4 key购买 nike

我找了又找。我找不到解决方案。我有一个字符串,有点像这样: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]/", "&nbsp;", $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';
}
?>

最佳答案

我无法重现你的问题,对我来说输出的字符串是:

$replaceUnder = 'ABC_test 001-2.jpg';
$makeSpace = preg_replace("/[^a-zA-Z0-9\s]/", "&nbsp;", $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';
}
?>

我认为您的整个问题都源于变量的命名。考虑打开通知错误 - 如果您正在引用 undefined variable ,它们会通知您。

关于PHP用空格替换每个非字母数字字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5281125/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com