2014-09-19 3 views
0

두 문자열에 PHP preg_replace 함수를 사용하고 싶지만 사용할 정규식이 확실하지 않습니다. BBCode 따옴표 태그에 대한 Preg_replace 패턴

[quote=username] 

:

[quote author=username link=1150111054/0#7 date=1150151926] 

결과 :

문자열이 들어, 난 단지 저자 값 (공백 후 이렇게 author= 후 모든 것을, 아무것도하지만)가 필요합니다 문자열에는 author= 태그가 없습니다. 사용자 이름은 단순히 폐쇄 개방 인용

[quote] username link=1142890417/0#43 date=1156429613] 

이상적 후 나타나는 결과는 같아야합니다

[quote=username] 

답변

1

author=]을 선택 사항 인 inorder로 만들어 두 유형의 문자열 모두에서 대체하십시오.

정규식 :

^\[(\S+?)\]?\s+(?:author=)?(\S+).*$ 

당신이 당신의 정규식은 다음 이것을 사용에 문자열 quote을 언급 할 경우,

^\[(quote)\]?\s+(?:author=)?(\S+).*$ 

교체 문자열 :

[$1=$2] 

DEMO

<?php 
$string =<<<EOT 
[quote author=username link=1150111054/0#7 date=1150151926] 
[quote] username link=1142890417/0#43 date=1156429613] 
EOT; 
echo preg_replace("~^\[(\S+?)\]?\s+(?:author=)?(\S+).*$~m", "[$1=$2]", $string); 
?> 

출력 : 여기에

[quote=username] 
[quote=username] 
+0

, 감사합니다. 두 번째 표현을 덜 욕심스럽게 만들기 위해 사용했습니다. 'pid = 123456'을 다음에서 제거하도록 표현식을 확장 할 수 있습니까 :'[quote = username pid = 123456]'? – ButtressCoral

+1

http://regex101.com/r/lH2fW8/5 –

+0

동일한 줄 문자열의 경우이 기능을 사용할 수 없습니다. 최종 닫는 대괄호까지 캡처하려고합니다.예 : http://regex101.com/r/zL4jY2/2 – ButtressCoral

1
첫 번째의 경우

: /author=(.*?) /

와의 두 번째 /\[quote\] (.*?) /

너의 경우 :

$str1 = "[quote author=username link=1150111054/0#7 date=1150151926]"; 
$str2 = "[quote] username link=1142890417/0#43 date=1156429613]"; 
$regex1 = '/author=(.*?) /'; 
$regex2 = '/\[quote\] (.*?) /'; 
if (preg_match($regex1, $str1, $match1)) 
    echo '[quote='.$newStr1 = $match1[1].']'; 
if (preg_match($regex2, $str2, $match2)) 
    echo '[quote='.$newStr2 = $match2[1].']'; 
0

은 하나의 정규식으로 모두 처리하는 또 다른 방법입니다.

# Find:  '~(?|\[quote\]\s*(\S+).*|\[quote\s+author=\s*(\S+).*)~' 
# Replace: '[author=$1]' 

(?| 
     \[quote\] \s* 
     (\S+) 
     .* 
    | 
     \[quote \s+ author= \s* 
     (\S+) 
     .* 
) 

입력 :

[quote author=username link=1150111054/0#7 date=1150151926] 
[quote] username link=1142890417/0#43 date=1156429613] 

출력 : 이것은 잘 작동

[author=username] 
[author=username]