[php] 특정 문자 뒤의 문자열 부분 제거

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;


답변

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

$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",",");
?>


답변

Austin의 답변은 귀하의 사례에 적합합니다.

더 일반적으로 분할하는 하위 문자열이 문자열마다 다를 수있는 경우 정규식 함수 를 살펴 보는 것이 좋습니다.

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