programing

문자열의 선두에서 문자열을 제거합니다.

sourcejob 2022. 11. 13. 19:31
반응형

문자열의 선두에서 문자열을 제거합니다.

다음과 같은 문자열이 있습니다.

$str = "bla_string_bla_bla_bla";

어떻게 하면 첫 번째를 제거할 수 있나요?bla_; 단, 스트링의 선두에 있는 경우에만요.

와 함께str_replace(), 모든 것을 삭제합니다. bla_

일반 형식(regex 없음):

$prefix = 'bla_';
$str = 'bla_string_bla_bla_bla';

if (substr($str, 0, strlen($prefix)) == $prefix) {
    $str = substr($str, strlen($prefix));
} 

소요시간: 0.0369밀리초(0.000,036,954초)

또, 이하에 대해서:

$prefix = 'bla_';
$str = 'bla_string_bla_bla_bla';
$str = preg_replace('/^' . preg_quote($prefix, '/') . '/', '', $str);

소요시간: 번째 실행(0.000,174,999초) 후 0.0510ms(0.000,051,021초)

내 서버에서 프로파일링한 게 분명해

캐럿 기호( )와 정규 표현을 사용할 수 있습니다.^): 스트링의 선두에 일치를 고정합니다.

$str = preg_replace('/^bla_/', '', $str);
function remove_prefix($text, $prefix) {
    if(0 === strpos($text, $prefix))
        $text = substr($text, strlen($prefix)).'';
    return $text;
}

보다 빠른 접근방식은 다음과 같습니다.

// strpos is faster than an unnecessary substr() and is built just for that 
if (strpos($str, $prefix) === 0) $str = substr($str, strlen($prefix));

여기서.

$array = explode("_", $string);
if($array[0] == "bla") array_shift($array);
$string = implode("_", $array);

속도도 좋지만, 이것은 _로 끝나는 바늘에 의존하도록 하드코드 되어 있습니다.일반 버전이 있나요?– todmo 6월 29일 23:26

일반 버전:

$parts = explode($start, $full, 2);
if ($parts[0] === '') {
    $end = $parts[1];
} else {
    $fail = true;
}

일부 벤치마크:

<?php

$iters = 100000;
$start = "/aaaaaaa/bbbbbbbbbb";
$full = "/aaaaaaa/bbbbbbbbbb/cccccccccc/dddddddddd/eeeeeeeeee";
$end = '';

$fail = false;

$t0 = microtime(true);
for ($i = 0; $i < $iters; $i++) {
    if (strpos($full, $start) === 0) {
        $end = substr($full, strlen($start));
    } else {
        $fail = true;
    }
}
$t = microtime(true) - $t0;
printf("%16s : %f s\n", "strpos+strlen", $t);

$t0 = microtime(true);
for ($i = 0; $i < $iters; $i++) {
    $parts = explode($start, $full, 2);
    if ($parts[0] === '') {
        $end = $parts[1];
    } else {
        $fail = true;
    }
}
$t = microtime(true) - $t0;
printf("%16s : %f s\n", "explode", $t);

꽤 오래된 홈 PC:

$ php bench.php

출력:

   strpos+strlen : 0.158388 s
         explode : 0.126772 s

많은 다른 답이 여기 있습니다.모두 문자열 분석에 기반을 둔 것 같습니다.PHP를 사용한 저의 견해는 다음과 같습니다.explode스트링을 정확히2개의 값의 배열로 분할하고 두 번째 값만 깔끔하게 반환합니다.

$str = "bla_string_bla_bla_bla";
$str_parts = explode('bla_', $str, 2);
$str_parts = array_filter($str_parts);
$final = array_shift($str_parts);
echo $final;

출력은 다음과 같습니다.

string_bla_bla_bla

PHP 8+ 에서는, 다음의 기능을 간단하게 사용할 수 있습니다.str_starts_with()기능:

$str = "bla_string_bla_bla_bla";
$prefix = "bla_";
if (str_starts_with($str, $prefix) {
  $str = substr($str, strlen($prefix));
}

https://www.php.net/manual/en/function.str-starts-with.php

subst_replace는 원하는 것을 할 수 있다고 생각합니다.이 경우 문자열의 일부에 치환을 제한할 수 있습니다.http://nl3.php.net/manual/en/function.substr-replace.php (이 경우 문자열의 선두만 볼 수 있습니다.)

count 파라미터 str_replace ( http://nl3.php.net/manual/en/function.str-replace.php )를 사용할 수 있습니다.이것에 의해, 치환의 수를 왼쪽부터 제한할 수 있습니다만, 선두에 강제적으로 설정할 수는 없습니다.

언급URL : https://stackoverflow.com/questions/4517067/remove-a-string-from-the-beginning-of-a-string

반응형