PHP用空格替换每个非字母数字字符
发布时间:2020-12-13 17:06:22 所属栏目:PHP教程 来源:网络整理
导读:我搜索并搜索过.我找不到解决方案.我有一个像这样的字符串:ABC_test 001-2.jpg 我也有这段代码: $makeSpace = preg_replace("/[^a-zA-Z0-9s]/","nbsp;",$replaceUnder); 但是,这段代码不会替换下划线(_).实际上,这个变量的输出是:ABC 所以它一旦击中下划
我搜索并搜索过.我找不到解决方案.我有一个像这样的字符串:ABC_test 001-2.jpg
我也有这段代码: $makeSpace = preg_replace("/[^a-zA-Z0-9s]/"," ",$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,-4); //removes file type from file name //$replaceUnder = str_replace("_","-",$class); $makeDash = str_replace(" ",$replaceUnder); $replaceUnder = preg_replace("/[^a-zA-Z0-9s]/"," ",$class); //$makeSpace = preg_replace("/[^a-zA-Z0-9s]/",$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-9s]/",$replaceUnder); print_r($makeSpace); # output: # ABC test 001 2 jpg . dubugging你的代码 我浏览了你粘贴的代码,发现了一些错误,可能是相关的,也许不是: 我在这一行收到错误,因为没有定义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-9s]/",$name); echo "Name: $fixedNamen"; } } } //if directory is empty throw an exception. catch(Exception $exc) { echo 'the directory you chose seems to be empty'; } ?> 我认为你的整个问题源于变量的命名.考虑启用通知错误 – 如果您引用未定义的变量,它们会通知您. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |