php 如何删除图像名称中的空格?[重复]

idv4meu8  于 5个月前  发布在  PHP
关注(0)|答案(8)|浏览(70)

此问题在此处已有答案

PHP replace all spaces with hyphens(1个答案)
Strip php variable, replace white spaces with dashes(3个答案)
How to replace whitespaces with dashes(2个答案)
6天前关闭
除了图像名称都是破折号之外,我还想将所有空格都改为破折号。

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

字符串

ebdffaop

ebdffaop1#

你可以尝试

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

字符串

vxbzzdmp

vxbzzdmp2#

简单空格可以使用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,句点和下划线-所有其他字符序列将被替换为一个破折号。在执行替换函数之前,文件名将被转换为所有小写字母。

btxsgosb

btxsgosb3#

只需要像下面这样用str_replace Package 输出。

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

字符串

hgtggwj0

hgtggwj04#

echo str_replace(' ', '-', strtolower(the_title('','',false)));

字符串

6pp0gazn

6pp0gazn5#

我最喜欢的用于消毒的正则表达式:

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

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

e0bqpujr

e0bqpujr6#

我不明白这样的替代品能有什么帮助。
如果你有一个实际的图像与空格的名称-它不会被显示后,取代。
你需要用urlencode()正确编码它
如果你想在图片名称中替换,你必须在图片上替换,而不是在链接上。
如果你需要任何“清理”它必须在图像上完成,而不是在链接上。
如果要对URI部分进行编码-使用urlencode()
程序员的每一个动作都必须是明智的选择,而不是随机挑选出来的

lmvvr0a8

lmvvr0a87#

您可以使用“strtolower()”将标题转换为破折号,使用“str_replace(' ','-',YOUR_STRING)”将标题中的所有空格替换为破折号。
尝试将您的代码替换为:

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

字符串
如果你想用更简单的形式来写,可以这样写:

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

2guxujil

2guxujil8#

$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 : '');
 }

字符串

相关问题