2015-01-19 4 views
-1

나는 PHP에서 시작하고있어 문자열의 모든 발생을 제거하려고합니다. 내 문자열은 그와 비슷한 것입니다.PHP에서 문자열의 발생을 제거

'This is [a test] try [it]' 

내가하려는 것은 대괄호 안에있는 텍스트가있는 []를 모두 제거하는 것입니다.

'This is try' 

:

나는 결과가 같은 것을 원한다.

어떻게 할 수 있습니까?

답변

3

preg_replace 기능을 사용할 수 있습니다. 하지만 닫는 괄호 ], 0 번 이상의 문자와 일치

preg_replace('~\[[^\]]*\]~', '', $string); 

[^\]]* 부정 문자 클래스.

여분의 다듬기 기능을 추가하여 결과 문자열에서 선행 또는 후행 공백을 제거하십시오.

$string = 'This is [a test] try [it]'; 
$result = preg_replace('~\[[^\]]*\]~', '', $string); 
echo trim($result, " "); 
+0

! 고마워! – Gustav

+0

환영합니다 ... –

0

이 작업을 시도 할 수 있습니다 :

$myString = 'This is [a test] try [it]'; 
$myString = preg_replace('/\[[\w ]+\] */', '', $myString); 
var_dump($myString); 

설명을 : 잘 작동

/\[[\w ]+\]/g 
\[ matches the character [ literally 
[\w ]+ match a single character present in the list below 
    Quantifier: + Between one and unlimited times, as many times as possible, giving back as needed [greedy] 
    \w match any word character [a-zA-Z0-9_] 
    ' ' the literal character ' ' 
\] matches the character ] literally 
관련 문제