문자열에서 확장을 제거하는 방법 (실제 확장 만!)
파일 이름에서 확장명을 제거 할 수있는 작은 기능을 찾고 있습니다.
인터넷 검색을 통해 많은 예를 찾았지만 "."로 문자열의 일부만 제거하기 때문에 나쁩니다. . 그들은 리미터에 점을 사용하고 문자열을 자릅니다.
이 스크립트들을보세요
$from = preg_replace('/\.[^.]+$/','',$from);
또는
$from=substr($from, 0, (strlen ($from)) - (strlen (strrchr($filename,'.'))));
다음과 같이 문자열을 추가하면
this.is somestring의 예입니다
"This"만 반환합니다 ...
확장자는 3 ~ 4자를 가질 수 있으므로 점이 4 또는 5 위치에 있는지 확인한 다음 제거해야합니다.
어떻게 할 수 있습니까?
이거 한번 해봐:
$withoutExt = preg_replace('/\\.[^.\\s]{3,4}$/', '', $filename);
따라서 이것은 점이나 공백이 아닌 3 ~ 4 개의 문자가 뒤에 오는 점과 일치합니다. 더 짧거나 더 긴 파일 확장자가 많으므로 "3 또는 4"규칙을 완화해야합니다.
http://php.net/manual/en/function.pathinfo.php
$filename = pathinfo('filename.md.txt', PATHINFO_FILENAME); // returns 'filename.md'
설명서에서 pathinfo :
<?php
$path_parts = pathinfo('/www/htdocs/index.html');
echo $path_parts['dirname'], "\n";
echo $path_parts['basename'], "\n";
echo $path_parts['extension'], "\n";
echo $path_parts['filename'], "\n"; // Since PHP 5.2.0
?>
제대로 작동하기위한 완벽한 경로 일 필요는 없습니다. 마찬가지로 행복하게 구문 분석 file.jpg
합니다 /path/to/my/file.jpg
.
(PHP 4, PHP 5)
var_dump(basename('test.php', '.php'));
출력 : string (4) "test"
이것은 다소 쉬운 해결책이며 문자열에 확장 시간이나 도트 또는 기타 문자 수에 관계없이 작동합니다.
$filename = "abc.def.jpg";
$newFileName = substr($filename, 0 , (strrpos($filename, ".")));
//$newFileName will now be abc.def
기본적으로 이것은 단지 마지막 발생을 찾습니다. 그런 다음 하위 문자열을 사용하여 해당 지점까지의 모든 문자를 검색합니다.
Google 예제 중 하나와 비슷하지만 정규 표현식 및 다른 예제보다 간단하고 빠르며 쉽습니다. 어쨌든 imo. 그것이 누군가를 돕기를 바랍니다.
PHP가 내장 한 것을 사용하여 도움을 줄 수 있습니다 ...
$withoutExt = pathinfo($path, PATHINFO_DIRNAME) . '/' . pathinfo($path, PATHINFO_FILENAME);
파일 이름 ( .somefile.jpg
) 만 다루면 ...
./somefile
아니면 정규식을 사용하십시오 ...
$withoutExt = preg_replace('/\.' . preg_quote(pathinfo($path, PATHINFO_EXTENSION), '/') . '$/', '', $path);
경로가 없지만 파일 이름 만 있으면 작동하며 훨씬 더 간결합니다 ...
$withoutExt = pathinfo($path, PATHINFO_FILENAME);
물론 둘 다 마지막 기간 ( .
)을 찾습니다 .
다음 코드는 저에게 효과적이며 꽤 짧습니다. 파일을 점으로 구분 된 배열로 나누고 마지막 요소 (가설 적으로 확장 인)를 삭제하고 점으로 배열을 다시 재구성합니다.
$filebroken = explode( '.', $filename);
$extension = array_pop($filebroken);
$fileTypeless = implode('.', $filebroken);
Google에서 많은 예제를 찾았지만 "."로 문자열의 일부를 제거하기 때문에 잘못되었습니다.
실제로 그것은 절대적으로 올바른 일입니다. 계속해서 사용하십시오.
The file extension is everything after the last dot, and there is no requirement for a file extension to be any particular number of characters. Even talking only about Windows, it already comes with file extensions that don't fit 3-4 characters, such as eg. .manifest
.
There are a few ways to do it, but i think one of the quicker ways is the following
// $filename has the file name you have under the picture
$temp = explode( '.', $filename );
$ext = array_pop( $temp );
$name = implode( '.', $temp );
Another solution is this. I havent tested it, but it looks like it should work for multiple periods in a filename
$name = substr($filename, 0, (strlen ($filename)) - (strlen (strrchr($filename,'.'))));
Also:
$info = pathinfo( $filename );
$name = $info['filename'];
$ext = $info['extension'];
// Or in PHP 5.4, i believe this should work
$name = pathinfo( $filename )[ 'filename' ];
In all of these, $name
contains the filename without the extension
$image_name = "this-is.file.name.jpg";
$last_dot_index = strrpos($image_name, ".");
$without_extention = substr($image_name, 0, $last_dot_index);
Output:
this-is.file.name
You can set the length of the regular expression pattern by using the {x,y}
operator. {3,4}
would match if the preceeding pattern occurs 3 or 4 times.
But I don't think you really need it. What will you do with a file named "This.is"?
As others mention, the idea of limiting extension to a certain number of characters is invalid. Going with the idea of array_pop, thinking of a delimited string as an array, this function has been useful to me...
function string_pop($string, $delimiter){
$a = explode($delimiter, $string);
array_pop($a);
return implode($delimiter, $a);
}
Usage:
$filename = "pic.of.my.house.jpeg";
$name = string_pop($filename, '.');
echo $name;
Outputs:
pic.of.my.house (note it leaves valid, non-extension "." characters alone)
In action:
http://sandbox.onlinephpfunctions.com/code/5d12a96ea548f696bd097e2986b22de7628314a0
Recommend use: pathinfo
with PATHINFO_FILENAME
$filename = 'abc_123_filename.html';
$without_extension = pathinfo($filename, PATHINFO_FILENAME);
Use this:
strstr('filename.ext','.',true);
//result filename
Try to use this one. it will surely remove the file extension.
$filename = "image.jpg";
$e = explode(".", $filename);
foreach($e as $key=>$d)
{
if($d!=end($e)
{
$new_d[]=$d;
}
}
echo implode("-",$new_t); // result would be just the 'image'
EDIT: The smartest approach IMHO, it removes the last point and following text from a filename (aka the extension):
$name = basename($filename, '.' . end(explode('.', $filename)));
Cheers ;)
This works when there is multiple parts to an extension and is both short and efficient:
function removeExt($path)
{
$basename = basename($path);
return strpos($basename, '.') === false ? $path : substr($path, 0, - strlen($basename) + strlen(explode('.', $basename)[0]));
}
echo removeExt('https://example.com/file.php');
// https://example.com/file
echo removeExt('https://example.com/file.tar.gz');
// https://example.com/file
echo removeExt('file.tar.gz');
// file
echo removeExt('file');
// file
참고URL : https://stackoverflow.com/questions/2395882/how-to-remove-extension-from-string-only-real-extension
'IT story' 카테고리의 다른 글
힘내 : 원격 지점 정보 업데이트 (0) | 2020.07.08 |
---|---|
TextView-프로그래밍 방식으로 텍스트 크기를 설정해도 작동하지 않는 것 같습니다 (0) | 2020.07.08 |
장면 뒤에 TypedReference가 왜 있습니까? (0) | 2020.07.08 |
Dagger 2에서 구성 요소 (오브젝트 그래프)의 수명주기를 결정하는 요소는 무엇입니까? (0) | 2020.07.08 |
동일한 벡터에서 요소를 푸시 백하는 것이 안전합니까? (0) | 2020.07.08 |