如何从字符串中删除扩展名(仅实际扩展名!) [英] How to remove extension from string (only real extension!)
问题描述
我正在寻找一个小的功能,该功能允许我从文件名中删除扩展名.
I'm looking for a small function that allows me to remove the extension from a filename.
我通过谷歌搜索找到了许多示例,但是它们很糟糕,因为它们只是用."删除了字符串的一部分. .他们使用点作为限制器,只是剪切字符串.
I've found many examples by googling, but they are bad, because they just remove part of the string with "." . They use dot for limiter and just cut string.
看看这些脚本,
$from = preg_replace('/\.[^.]+$/','',$from);
或
$from=substr($from, 0, (strlen ($from)) - (strlen (strrchr($filename,'.'))));
当我们添加这样的字符串时:
When we add the string like this:
这是字符串的例子
This.is example of somestring
它将仅返回"This" ...
It will return only "This"...
扩展名可以包含3个或4个字符,因此我们必须检查点是否位于4或5个位置,然后将其删除.
The extension can have 3 or 4 characters, so we have to check if dot is on 4 or 5 position, and then remove it.
怎么办?
推荐答案
尝试以下方法:
$withoutExt = preg_replace('/\\.[^.\\s]{3,4}$/', '', $filename);
因此,它匹配一个点,后跟三个或四个不是点或空格的字符.应该放宽"3或4"规则,因为有很多文件扩展名短些或长一些.
So, this matches a dot followed by three or four characters which are not a dot or a space. The "3 or 4" rule should probably be relaxed, since there are plenty of file extensions which are shorter or longer.
这篇关于如何从字符串中删除扩展名(仅实际扩展名!)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!