programing

문자열의 일부만 제거하지만 문자열 끝에 있는 경우에만 제거

luckcodes 2022. 10. 28. 22:04

문자열의 일부만 제거하지만 문자열 끝에 있는 경우에만 제거

문자열의 하위 문자열을 제거해야 하지만 문자열 끝에 있는 경우에만 제거해야 합니다.

예를 들어, 다음 문자열의 끝에 있는 'string'을 삭제합니다.

"this is a test string" ->  "this is a test "
"this string is a test string" - > "this string is a test "
"this string is a test" -> "this string is a test"

어떤 아이디어라도? 아마도 대체품일거야, 하지만 어떻게?

의 사용에 주의해 주십시오.$문자열의 끝을 나타내는 문자:

$new_str = preg_replace('/string$/', '', $str);

문자열이 사용자 지정 변수인 경우 먼저 실행해 보는 것이 좋습니다.

$remove = $_GET['remove']; // or whatever the case may be
$new_str = preg_replace('/'. preg_quote($remove, '/') . '$/', '', $str);

서브스트링에 특수 문자가 포함되어 있는 경우 regexp 사용이 실패할 수 있습니다.

다음은 임의의 문자열로 동작하며 삽입 문자열 함수에 의해 사용되는 규칙을 따릅니다.

function right_trim(string $haystack, string $needle): string {
    $needle_length = strlen($needle);
    if (substr($haystack, -$needle_length) === $needle) {
        return substr($haystack, 0, -$needle_length);
    }
    return $haystack;
}

현의 왼쪽과 오른쪽 트림에 대해 다음 두 가지 함수를 작성했습니다.

/**
 * @param string    $str           Original string
 * @param string    $needle        String to trim from the end of $str
 * @param bool|true $caseSensitive Perform case sensitive matching, defaults to true
 * @return string Trimmed string
 */
function rightTrim($str, $needle, $caseSensitive = true)
{
    $strPosFunction = $caseSensitive ? "strpos" : "stripos";
    if ($strPosFunction($str, $needle, strlen($str) - strlen($needle)) !== false) {
        $str = substr($str, 0, -strlen($needle));
    }
    return $str;
}

/**
 * @param string    $str           Original string
 * @param string    $needle        String to trim from the beginning of $str
 * @param bool|true $caseSensitive Perform case sensitive matching, defaults to true
 * @return string Trimmed string
 */
function leftTrim($str, $needle, $caseSensitive = true)
{
    $strPosFunction = $caseSensitive ? "strpos" : "stripos";
    if ($strPosFunction($str, $needle) === 0) {
        $str = substr($str, strlen($needle));
    }
    return $str;
}

정규 표현식을 사용해도 될 것 같은데string그 다음, 현의 끝과 함수가 결합됩니다.


다음과 같은 것이 정상적으로 동작합니다.

$str = "this is a test string";
$new_str = preg_replace('/string$/', '', $str);


주의:

  • string일치...뭐... string
  • 그리고.$문자열의 끝을 의미합니다.

자세한 내용은 PHP 매뉴얼의 패턴 구문 섹션을 참조하십시오.

preg_replace 및 다음 패턴 : /string\z/i

\z는 문자열의 끝을 의미합니다.

http://tr.php.net/preg_replace

성능에 개의치 않고 문자열의 일부를 문자열 끝에만 배치할 수 있는 경우 다음을 수행할 수 있습니다.

$string = "this is a test string";
$part = "string";
$string = implode( $part, array_slice( explode( $part, $string ), 0, -1 ) );
echo $string;
// OUTPUT: "this is a test "

@Skrol29의 답변이 가장 좋지만, 여기에서는 함수 형태로 3진 연산자를 사용하고 있습니다.

if (!function_exists('str_ends_with')) {
    function str_ends_with($haystack, $suffix) {
        $length = strlen( $suffix );
        if( !$length ) {
            return true;
        }
        return substr( $haystack, -$length ) === $suffix;
    }
}

if (!function_exists('remove_suffix')) {
    function remove_suffix ($string, $suffix) {
        return str_ends_with($string, $suffix) ? substr($string, 0, strlen($string) - strlen($suffix)) : $string;
    }
}

PHP 8 버전

function removePostfix(string $haystack, string $needle): string
{
    if (str_ends_with($haystack, $needle)) {
        return substr($haystack, 0, strlen($haystack) - strlen($needle));
    }


    return $haystack;
}

PHP 4 이후부터 이 기능을 사용하기 위한 빌트인 기능을 본 적이 없다는 것은 매우 놀랍습니다.

간단하게 사용할 수 있습니다.rtrim이 일을 하기 위해서.테스트해 본 적은 없지만rtrim훨씬 더, 훨씬 더 빠를 것이 거의 확실합니다.preg_replace이는 regexp 엔진에 의존하지 않기 때문에 다른 답변에서 권장됩니다.

rtrim("this is a test string", "string"); 
// Returns: "this is a test "

자세한 내용은 rtrim 매뉴얼페이지에서 확인하실 수 있습니다.

언급URL : https://stackoverflow.com/questions/5573334/remove-a-part-of-a-string-but-only-when-it-is-at-the-end-of-the-string