programing

PHP: 괄호 안의 텍스트를 추출하는 가장 좋은 방법?

minecode 2022. 10. 11. 21:21
반응형

PHP: 괄호 안의 텍스트를 추출하는 가장 좋은 방법?

괄호 사이에 있는 텍스트 세트를 추출하는 가장 효과적인 방법은 무엇입니까?"이(텍스트)를 제외한 모든 것을 무시함" 문자열에서 "텍스트" 문자열을 가장 효율적인 방법으로 가져오고 싶다고 가정합니다.

지금까지 제가 생각해낸 가장 좋은 점은 다음과 같습니다.

$fullString = "ignore everything except this (text)";
$start = strpos('(', $fullString);
$end = strlen($fullString) - strpos(')', $fullString);

$shortString = substr($fullString, $start, $end);

더 좋은 방법이 있을까요?일반적으로 regex를 사용하는 것이 효율이 떨어지는 것은 알고 있습니다만, 함수 호출 수를 줄일 수 없는 한 이것이 가장 좋은 방법일까요?생각?

그냥 regex를 찍어서 끝냈을 거야퍼포먼스의 큰 문제가 될 정도로 반복하고 있지 않는 한, 코딩을 간단하게 할 수 있습니다(다시 생각해 보면 이해할 수 있습니다).

$text = 'ignore everything except this (text)';
preg_match('#\((.*?)\)#', $text, $match);
print $match[1];

그래서 실제로 당신이 올린 코드가 작동하지 않습니다.substr()'s파라미터는 $string, $start 및 $length 입니다.strpos()'s는 '''입니다.$haystack,$needle 간간: :

$str = "이것(텍스트)"을 제외한 모든 항목 표시";$start = strpossecstr, '(')';$end = strpossecstr, '), $start + 1);$length = $end - $start;$result = substartstr, $start + 1, $length - 1);

몇 가지 세부 사항:나는 사용했다$start + 1php를 합니다.strpos()하면, 는 increment search search 번 、 괄 、 합 、 니 、 합 、 합 니 。$start과 1을 줄이다$length괄호를 제외합니다.

이에는 에러 체크가 확인해 주세요.$start ★★★★★★★★★★★★★★★★★」$end전 === false === false를 하지 마십시오.substr.

strpos/substr이 먼저 됩니다.vs regex ; gegegegegegegegege 。★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★ 숨쉬다strpos/substr그래서 별로 신경 쓰지 않지만, 다른 누군가가 regex의 콤팩트함을 선호할 수도 있습니다.

정규 표현 사용:

if( preg_match( '!\(([^\)]+)\)!', $text, $match ) )
    $text = $match[1];

문자열의 첫 번째 괄호 사이에 단어를 넣는 가장 빠른 방법이라고 생각합니다.

$string = 'ignore everything except this (text)';
$string = explode(')', (explode('(', $string)[1]))[0];
echo $string;

게시된 - regex -\((.*?)\) ★★★★★★★★★★★★★★★★★」\(([^\)]+)\)- 열린 괄호와 닫힌 괄호 사이의 가장 안쪽 문자열을 반환하지 마십시오.문자열이Text (abc(xyz 123) 다 a를 반환한다.(abc(xyz 123)아니라 (xyz 123).

(「」와 함께 )preg_match와 첫 번째를 preg_match_all모든 오카렌스를 가져오려면 괄호 안에 다른 열린 괄호 및 닫힌 괄호 없이 괄호 안에 있어야 합니다.

\([^()]*\)

또는 괄호 없이 값을 가져옵니다.

\(([^()]*)\)        // get Group 1 values after a successful call to preg_match_all, see code below
\(\K[^()]*(?=\))    // this and the one below get the values without parentheses as whole matches 
(?<=\()[^()]*(?=\)) // less efficient, not recommended

교체하다*와 함께+사이에 적어도 1글자가 있어야 하는 경우(그리고.).

상세:

  • \(- 여는 둥근 괄호(문자 클래스 외부에서 사용되는 리터럴 괄호를 나타내려면 이스케이프해야 함)
  • [^()]*- 0자 이상 (외)(그리고.)(주의:(그리고.)문자 클래스 내에서 탈출할 필요가 없습니다.(그리고.)그룹 지정에 사용할 수 없으며 리터럴 괄호로 처리됩니다.)
  • \)- 닫는 둥근 괄호(문자 클래스 외부에서 사용되는 리터럴 괄호를 나타내려면 이스케이프해야 합니다).

\(\K정규식 대체 시합에 참가하다(일치값에서 제외됩니다(단,\K일치 리셋 연산자). (?<=\()긍정적인 이면을 바라볼 때(현재 위치 왼쪽에 바로 표시되지만(는 룩백(룩어라운드) 패턴이 소비되지 않기 때문에 일치 값에 추가되지 않습니다. (?=\()긍정적인 예측이 필요하기 때문에)char를 선택하면 현재 위치의 오른쪽에 바로 나타납니다.

PHP 코드:

$fullString = 'ignore everything except this (text) and (that (text here))';
if (preg_match_all('~\(([^()]*)\)~', $fullString, $matches)) {
    print_r($matches[0]); // Get whole match values
    print_r($matches[1]); // Get Group 1 values
}

출력:

Array ( [0] => (text)  [1] => (text here) )
Array ( [0] => text    [1] => text here   )

이것은 '['와 '] 사이의 모든 텍스트를 추출하여 2개의 배열로 저장하기 위한 샘플 코드입니다(한 배열에 괄호 안에 있는 텍스트와 다른 배열에 있는 괄호 밖에 있는 텍스트).

   function extract_text($string)
   {
    $text_outside=array();
    $text_inside=array();
    $t="";
    for($i=0;$i<strlen($string);$i++)
    {
        if($string[$i]=='[')
        {
            $text_outside[]=$t;
            $t="";
            $t1="";
            $i++;
            while($string[$i]!=']')
            {
                $t1.=$string[$i];
                $i++;
            }
            $text_inside[] = $t1;

        }
        else {
            if($string[$i]!=']')
            $t.=$string[$i];
            else {
                continue;
            }

        }
    }
    if($t!="")
    $text_outside[]=$t;

    var_dump($text_outside);
    echo "\n\n";
    var_dump($text_inside);
  }

출력: extract_text("hello how are?"")는 다음을 생성합니다.

array(1) {
  [0]=>
  string(18) "hello how are you?"
}

array(0) {
}

extract_textsechello [ http://www.google.com/test.mp3 ]안녕하세요?)를 작성하겠습니다.

array(2) {
  [0]=>
  string(6) "hello "
  [1]=>
  string(13) " how are you?"
}


array(1) {
  [0]=>
  string(30) "http://www.google.com/test.mp3"
}

이 기능은 유용할 수 있습니다.

    public static function getStringBetween($str,$from,$to, $withFromAndTo = false)
    {
       $sub = substr($str, strpos($str,$from)+strlen($from),strlen($str));
       if ($withFromAndTo)
         return $from . substr($sub,0, strrpos($sub,$to)) . $to;
       else
         return substr($sub,0, strrpos($sub,$to));
    }
    $inputString = "ignore everything except this (text)";
    $outputString = getStringBetween($inputString, '(', ')'));
    echo $outputString; 
    //output will be test

    $outputString = getStringBetween($inputString, '(', ')', true));
    echo $outputString; 
    //output will be (test)

strpos() = > 문자열에서 첫 번째 발생 위치를 찾기 위해 사용됩니다.

strpos() = > 문자열에서 첫 번째 발생 위치를 찾기 위해 사용됩니다.

function getStringsBetween($str, $start='[', $end=']', $with_from_to=true){
$arr = [];
$last_pos = 0;
$last_pos = strpos($str, $start, $last_pos);
while ($last_pos !== false) {
    $t = strpos($str, $end, $last_pos);
    $arr[] = ($with_from_to ? $start : '').substr($str, $last_pos + 1, $t - $last_pos - 1).($with_from_to ? $end : '');
    $last_pos = strpos($str, $start, $last_pos+1);
}
return $arr; }

이는 모든 패턴을 어레이 형식으로 반환하는 이전 답변보다 약간 개선된 것입니다.

getStringsBetween('[T]his[] is [test] string [pattern])'이 반환됩니다.

언급URL : https://stackoverflow.com/questions/196520/php-best-way-to-extract-text-within-parenthesis

반응형