Nice programing

괄호 사이의 텍스트 제거 PHP

nicepro 2020. 12. 2. 21:59
반응형

괄호 사이의 텍스트 제거 PHP


PHP에서 괄호 세트와 괄호 사이의 텍스트를 제거하는 방법이 궁금합니다.

예 :

ABC (Test1)

(Test1) 삭제하고 ABC 만 남기고 싶습니다.

감사


$string = "ABC (Test1)";
echo preg_replace("/\([^)]+\)/","",$string); // 'ABC '

preg_replace펄 기반 정규식 교체 루틴입니다. 이 스크립트가 수행하는 작업은 여는 괄호와 닫는 괄호가 아닌 문자 , 그리고 다시 닫는 괄호가 뒤 따르는 모든 문자와 일치 한 다음 삭제하는 것입니다.

정규식 분석 :

/  - opening delimiter (necessary for regular expressions, can be any character that doesn't appear in the regular expression
\( - Match an opening parenthesis
[^)]+ - Match 1 or more character that is not a closing parenthesis
\) - Match a closing parenthesis
/  - Closing delimiter

허용되는 대답은 중첩되지 않은 괄호에 적합합니다. 정규식을 약간 수정하면 중첩 된 괄호에서 작동 할 수 있습니다.

$string = "ABC (Test1(even deeper) yes (this (works) too)) outside (((ins)id)e)";
echo preg_replace("/\(([^()]*+|(?R))*\)/","", $string);

정규식없이

$string="ABC (test)"
$s=explode("(",$string);
print trim($s[0]);

$string = "ABC (Test1(even deeper) yes (this (works) too)) outside (((ins)id)e)";
$paren_num = 0;
$new_string = '';
foreach($string as $char) {
    if ($char == '(') $paren_num++;
    else if ($char == ')') $paren_num--;
    else if ($paren_num == 0) $new_string .= $char;
}
$new_string = trim($new_string);

괄호를 세면서 각 문자를 반복하여 작동합니다. $paren_num == 0(모든 괄호 밖에있을 때) 경우 에만 결과 문자열에 문자를 추가합니다 $new_string.


여러분, 정규 표현식은 비정규 언어를 구문 분석하는 데 사용할 수 없습니다. 비정규 언어는 해석을 위해 상태를 요구하는 언어입니다 (즉, 현재 열려있는 괄호 수 기억).

위의 모든 답변은 "ABC (hello (world) how are you)"문자열에서 실패합니다.

Jeff Atwood의 Parsing Html The Cthulhu Way : https://blog.codinghorror.com/parsing-html-the-cthulhu-way/를 읽은 다음 직접 작성된 파서를 사용합니다 (문자열의 문자를 반복합니다. 문자가 괄호인지 아닌 경우 스택을 유지하거나 컨텍스트없는 언어를 구문 분석 할 수있는 렉서 / 파서를 사용합니다.

"올바르게 일치하는 괄호의 언어"에 대한이 위키피디아 문서도 참조하십시오. https://en.wikipedia.org/wiki/Dyck_language


가장 빠른 방법 (프리그 제외) :

$str='ABC (TEST)';
echo trim(substr($str,0,strpos($str,'(')));

단어 끝에서 공백을 자르지 않으려면 코드에서 자르기 기능을 제거하십시오.


$str ="ABC (Test1)";    
echo preg_replace( '~\(.*\)~' , "", $str );      

참고 URL : https://stackoverflow.com/questions/2174362/remove-text-between-parentheses-php

반응형