如何删除图像名称中的空格?

问题描述 投票:0回答:7

除了将图像名称全部小写之外,我还想将所有空格更改为破折号。

<img src="/SC/images/<?php echo strtolower(the_title('','',false)); ?>-header.jpg" border="0" />
php wordpress replace lowercase
7个回答
2
投票

你可以试试

 move_uploaded_file($_FILES["file"]["tmp_name"],"product_image/" . str_replace(" ","_",$_FILES["file"]["name"]));

1
投票

可以使用

str_replace()
删除简单的空格:

$image = "foo and bar.png";

// foo-and-bar.png
echo str_replace( " ", "-", $image );

可以使用正则表达式完成更复杂的搜索/替换:

$image = "foo2   and_ BAR.png";

// foo2-and_-bar.png
echo preg_replace( "/[^a-z0-9\._]+/", "-", strtolower($image) );

在此示例中,我们允许使用字母 a-z、数字 0-9、句点和下划线 - 所有其他字符序列都将替换为单个破折号。在运行替换函数之前,文件名将全部转换为小写。


0
投票

只需使用 str_replace 包装输出,如下所示。

<img src="/SC/images/<?php echo str_replace(" ", "-", strtolower(the_title('','',false))); ?>-header.jpg" border="0" />

0
投票
echo str_replace(' ', '-', strtolower(the_title('','',false)));

0
投票

我最喜欢的正则表达式用于清理:

echo strtolower( preg_replace( '/[^a-zA-Z0-9\-]/', '', preg_replace( '/\s/g', '-', the_title( '', '', false ) ) ) );

这将删除所有非字母数字字符。


0
投票
我不明白这样的替换有什么帮助。

如果您有名称中带有空格的实际图像 - 替换后将不会显示。
你需要用
urlencode()

 来正确编码它

如果要替换图片名称,则必须在图片上进行替换,而不是在链接上进行。

如果您需要任何“清理”,则必须在图像上完成,而不是在链接上完成。
如果你想编码 URI 部分 - 使用
urlencode()

 

每个程序员的行动都必须经过明智的选择,而不是凭空随机挑选


0
投票

$path = strtolower(the_title('','',false)).'.header.jpg'; $filepath = formatfilename($path); // remove space and special character from basename of file. <img src="/SC/images/<?php echo $filepath;?>" border="0" /> function formatfilename($filename) { $fileInfo = pathinfo($filename); $extension = isset($fileInfo['extension']) ? $fileInfo['extension'] : ''; // Remove special characters and replace spaces with underscores $formattedfilename = preg_replace('/[^a-zA-Z0-9]+/', '_', $fileInfo['filename']); // Remove leading and trailing underscores $formattedfilename = trim($formattedfilename, '_'); return $formattedfilename . ($extension ? '.' . $extension : ''); }

© www.soinside.com 2019 - 2024. All rights reserved.