programing

특정 문자 뒤에 문자열 부분 제거

itsource 2022. 10. 14. 21:51
반응형

특정 문자 뒤에 문자열 부분 제거

PHP의 특정 서브스트링 후에 어떻게 모든 것을 제거할 수 있는지 궁금할 뿐입니다.

예:

Posted On April 6th By Some Dude

하위 문자열 "By"를 포함한 모든 텍스트를 제거하도록 하고 싶습니다.

감사해요.

$variable = substr($variable, 0, strpos($variable, "By"));

쉬운 영어: 끈의 선두에서 시작하여 제거기와 처음 마주치는 위치에서 끝나는 부분을 주세요.

PHP 5.3+를 사용하는 경우 strstr()의 $before_needle 플래그를 확인합니다.

$s = 'Posted On April 6th By Some Dude';
echo strstr($s, 'By', true);

를 사용하는 것은 어떻습니까?explode:

$input = 'Posted On April 6th By Some Dude';
$result = explode(' By',$input);
return $result[0];

장점:

다음과 같은 작업을 할 수 있습니다.

$posted = preg_replace('/ By.*/', '', $posted);
echo $posted;

이것은 리터럴 문자열을 찾는 정규 표현식 리페이서 함수입니다. By' 및 그 뒤의 임의의 문자(.*를 빈 문자열로 바꿉니다( ).''), 같은 변수에 결과를 저장합니다( ).$posted)가 검색되었습니다.

한다면[space]By입력 문자열에 없습니다.문자열은 변경되지 않습니다.

한 가지 방법은 다음과 같습니다.

$str = 'Posted On April 6th By Some Dude';
echo strtok($str, 'By'); // Posted On April 6th

이거 먹어봐.

function strip_after_string($str,$char)
    {
        $pos=strpos($str,$char);    
        if ($pos!==false) 
        {
            //$char was found, so return everything up to it.
            return substr($str,0,$pos);
        } 
        else 
        {
            //this will return the original string if $char is not found.  if you wish to return a blank string when not found, just change $str to ''
            return $str; 
        }
    }

사용방법:

<?php
    //returns Apples
    $clean_string= strip_after_string ("Apples, Oranges, Banannas",",");
?>

오스틴의 답변은 당신의 사례에서 유효합니다.

일반적으로 분할하는 부분 문자열이 문자열마다 다를 수 있는 경우 정규 표현 함수를 알아보는 것이 좋습니다.

$190 = preg_replace('/By).*/', '', $120);

및 기능을 사용할 수 있습니다.

list($result) = explode("By", "Posted On April 6th By Some Dude", 2);
// $result is "Posted On April 6th "
$var = "Posted On April 6th By Some Dude";
$new_var = substr($var, 0, strpos($var, " By"));

preg_replace 에는 다음 한 가지 방법이 있습니다.

$newText = preg_replace('/\bBy\b.*$/', '', $text);

'\b'는 단어 경계(폭 제로이며 단어와 비단어 문자 간의 일치)와 일치하므로 완전한 단어에만 일치합니다.이 예에서는 타깃 워드가 다른 워드의 일부로 나타나지 않지만 일반적으로 타깃이 다른 워드의 일부로 나타날 수 있습니다(예: F의 "Babilon Revisited"의 "by").Scott Fitzgerald" 또는 "Bloom County Babilon by Berkeley Breaden").

'.*$'는 마지막까지 모든 텍스트와 일치합니다.'$'는 문자열의 끝에 일치하며 정확성을 위해 반드시 필요한 것은 아니지만 regex(읽기 어려워지는 것으로 잘 알려져 있음)의 의도를 문서화합니다).

정규 표현 조회는 문자열 시작부터 시작되므로 첫 번째 일치부터 대체됩니다.마지막에서 시작하는 일치 방법에 대해서는 "문자열의 마지막 일치만 preg_replace로 바꾸는 방법"을 참조하십시오.

: " " " "$string = preg_replace('/\s+By.*$/', '', $string)

아래는 문자열의 첫 번째 By 뒤에 있는 모든 것을 끊는 가장 효율적인 방법입니다(실행 시간 기준).By가 존재하지 않는 경우 완전한 문자열이 반환됩니다.결과는 $sResult입니다.

$sInputString = "Posted On April 6th By Some Dude";
$sControl = "By";

//Get Position Of 'By'
$iPosition = strpos($sInputString, " ".$sControl);
if ($iPosition !== false)
  //Cut Off If String Exists
  $sResult = substr($sInputString, 0, $iPosition);
else
  //Deal With String Not Found
  $sResult = $sInputString;

//$sResult = "Posted On April 6th"

대소문자를 구분하지 않으려면 strpos 대신 stripos를 사용합니다.By가 여러 번 존재할 수 있다고 생각되며 마지막 발생 후 모든 항목을 잘라내려면 strpos를 사용합니다.

아래는 효율은 떨어지지만 코드 공간을 적게 차지합니다.또한 이 방법은 보다 유연하며 정규 표현을 수행할 수 있습니다.

$sInputString = "Posted On April 6th By Some Dude";
$pControl = "By";

$sResult = preg_replace("' ".$pControl.".*'s", '', $sInputString);

//$sResult = "Posted On April 6th"

예를 들어, 하루 후에 모든 항목을 제거하는 경우:

$sInputString = "Posted On April 6th By Some Dude";
$pControl = "[0-9]{1,2}[a-z]{2}"; //1 or 2 numbers followed by 2 lowercase letters.

$sResult = preg_replace("' ".$pControl.".*'s", '', $sInputString);

//$sResult = "Posted On April"

대소문자를 구분하지 않는 경우 다음과 같이 i 수식자를 추가합니다.

$sResult = preg_replace("' ".$pControl.".*'si", '', $sInputString);

마지막 항목을 모두 통과시키려면 두 개 이상 있을 수 있다고 생각되는 경우 시작 부분에 다음과 같이 .*를 추가합니다.

$sResult = preg_replace("'.* ".$pControl.".*'si", '', $sInputString);

그러나 preg_match를 사용하여 실행하려는 작업을 수행할 수 있는 매우 강력한 방법도 있습니다.

$sInputString = "Posted On April 6th By Some Dude";

$pPattern = "'Posted On (.*?) By (.*?)'s";
if (preg_match($pPattern, $sInputString, $aMatch)) {
  //Deal With Match
  //$aMatch[1] = "April 6th"
  //$aMatch[2] = "Some Dude"
} else {
  //No Match Found
}

정규 표현은 처음에는 혼란스러워 보일 수 있지만, 일단 그것들을 숙달하면 매우 강력하고 여러분의 가장 친한 친구가 될 수 있습니다!행운을 빕니다.

왜...

이것은 대부분의 사람들의 요구에 과잉 살상일 가능성이 높지만, 위에서 대답한 개인들은 그렇지 않은 많은 것들을 다루고 있습니다.그 중 3개는 저의 필요에 따라 필요했습니다.엄격한 괄호로 묶고 코멘트를 삭제해도 13줄의 코드에서만 읽을 수 있습니다.

여기에는 다음 사항이 포함됩니다.

  • REGEX vs strpos/strripos/stristr 사용 시 퍼포먼스에 미치는 영향
  • 문자열에서 문자/문자열을 찾을 수 없는 경우 stripos/strpos를 사용합니다.
  • 문자열 왼쪽 또는 오른쪽에서 삭제(처음 또는 마지막 항목).
  • CoSe Sensitivity.
  • 검색 문자/문자열을 찾을 수 없는 경우 원래 문자열을 변경하지 않고 반환할 수 있는 기능을 원합니다.

사용방법:

원래 문자열, 검색 문자/문자열, 오른쪽 또는 왼쪽에서 시작하는 경우 "R"/"L"을 보내고 대소문자를 구분하는 경우 true/false를 보냅니다.예를 들어, "여기" 대소문자를 구분하지 않고 문자열에서 오른쪽부터 시작합니다.

echo TruncStringAfterString("Now Here Are Some Words Here Now","here","R",false);

출력은 "Now Here Are Some Words"가 됩니다."R"을 "L"로 변경하면 "Now"가 출력됩니다.

기능은 다음과 같습니다.

function TruncStringAfterString($origString,$truncChar,$startSide,$caseSensitive)
{
    if ($caseSensitive==true && strstr($origString,$truncChar)!==false)
    {
        // IF START RIGHT SIDE:
        if (strtoupper($startSide)=="R" || $startSide==false)
        {   // Found, strip off all chars from truncChar to end
            return substr($origString,0,strrpos($origString,$truncChar));
        }

        // IF START LEFT SIDE: 
        elseif (strtoupper($startSide)=="L" || $startSide="" || $startSide==true)
        {   // Found, strip off all chars from truncChar to end
            return strstr($origString,$truncChar,true);
        }           
    }
    elseif ($caseSensitive==false && stristr($origString,$truncChar)!==false)
    {           
        // IF START RIGHT SIDE: 
        if (strtoupper($startSide)=="R" || $startSide==false)
        {   // Found, strip off all chars from truncChar to end
            return substr($origString,0,strripos($origString,$truncChar));
        }

        // IF START LEFT SIDE: 
        elseif (strtoupper($startSide)=="L" || $startSide="" || $startSide==true)
        {   // Found, strip off all chars from truncChar to end
            return stristr($origString,$truncChar,true);
        }
    }       
    else
    {   // NOT found - return origString untouched
        return $origString;     // Nothing to do here
    }           

}

strstr 함수를 사용합니다.

<?php
$myString = "Posted On April 6th By Some Dude";
$result = strstr($myString, 'By', true);

echo $result ;

파라미터 " " " "true두 번째 파라미터가 처음 발생하기 전에 모든 것을 반환하도록 함수에 지시합니다.

"By" 뒤에 오는 문자를 치환하고 싶은 사람에게 도움이 될 것 같아서 예를 들어 문자열의 20번째 위치에 있는 텍스트에서 by를 무시하려면 위치에 + 2를 추가해야 합니다. 그러면 20번째 위치가 무시되고 by가 온 후에 모두 치환됩니다.치환할 텍스트의 정확한 문자 길이를 지정합니다.

$variable = substr($variable, 0, strpos($variable, "By") + 2 );
$variable = substr($initial, 0, strpos($initial, "By"));

if (!empty($variable)) { echo $variable; } else { echo $initial; }

언급URL : https://stackoverflow.com/questions/2588666/remove-portion-of-a-string-after-a-certain-character

반응형