programing tip

문자열의 일부를 제거하지만 문자열의 끝에있을 때만

itbloger 2020. 11. 1. 17:24
반응형

문자열의 일부를 제거하지만 문자열의 끝에있을 때만


문자열의 하위 문자열을 제거해야하지만 문자열의 END에있을 때만 해당됩니다.

예를 들어, 다음 문자열의 끝에서 '문자열'을 제거합니다.

"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"

어떤 생각? 아마도 어떤 종류의 preg_replace 일 것입니다. 그러나 어떻게 ??


$문자열의 끝을 나타내는 문자 의 사용에 주목할 것입니다 .

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

문자열이 사용자가 제공 한 변수 인 경우 preg_quote먼저 실행하는 것이 좋습니다 .

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

하위 문자열에 특수 문자가있는 경우 regexp 사용이 실패 할 수 있습니다.

다음은 모든 문자열에서 작동합니다.

$substring = 'string';
$str = "this string is a test string";
if (substr($str,-strlen($substring))===$substring) $str = substr($str, 0, strlen($str)-strlen($substring));

문자열의 왼쪽 및 오른쪽 트림에 대해 다음 두 함수를 작성했습니다.

/**
 * @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하고 그다음 함수 와 결합 된 string의 끝입니다preg_replace() .


이와 같은 것이 잘 작동합니다.

$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 "

rtrim () 사용할 수 있습니다 .

php > echo rtrim('this is a test string', 'string');
this is a test 

이것은 'string'문자 마스크와 문자 순서가 존중되지 않으므로 일부 경우에만 작동합니다 .

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

반응형