2017-05-05 1 views
0

_ 뒤에 문자열을 검색하기 위해 preg_match_all() 함수를 사용하려고했습니다. 내가 원하는 출력은 reset,text,email입니다. 내가 regexr 편집기를 사용하여 그것을 만들려고했는데 [_]+[a-z]*으로 만들 수 있지만 _reset, _text, _text이 포함됩니다. 문자열은 다음과 같습니다밑줄 앞뒤에 부분 문자열 추출

$str = 'button_reset,location_text,email_text'; 

예상 출력 :

reset 
text 
email 
+0

귀하의 예상 출력은 이해가되지 않습니다. "전자 메일"은 밑줄 뒤에 표시되지 않습니다. –

답변

2

이것에 대한 정규식을 피하기 위해 더 좋을 것입니다 작업 그냥 사용 str_replace() :

입력 :

$str = 'button_reset,location_text,email_text'; 

코드 배열로 출력 :

var_export(explode(',',str_replace(['button_reset','location_text','email_text'],['reset','text','email'],$str))); 
// array (
// 0 => 'reset', 
// 1 => 'text', 
// 2 => 'email', 
//) 

또는 당신이 주장하는 경우, 정규식 (Demo Link) :

/button_\K[^,]+|,location_\K[^,]+|,\K[^_]+(?=_text)/ 

정규식 고장 :

button_\K[^,]+  #Match one or more non-comma-characters after button_ 
|     #or 
,location_\K[^,]+ #Match one or more non-comma-characters after location_ 
|     #or 
,\K[^_]+(?=_text) #Match one or more non-underscore-characters that are 
        # immediately followed by _textafter button_ 

각 조건식의 \K이 점에서 일치를 의미 효과적으로이 경우에 캡처 그룹을 사용할 필요가 제거합니다. 캡처 그룹을 사용하는 경우 preg_match_all()은 전체 문자열 일치로 채워지는 하위 배열과 캡처 된 값으로 적어도 하나 이상의 하위 배열을 만듭니다. \K은 배열 크기를 최대 50 %까지 줄일 수 있으므로 가능한 한 항상 사용해야합니다.

코드 :

$array=preg_match_all('/button_\K[^,]+|,location_\K[^,]+|,\K[^_]+(?=_text)/',$str,$out)?$out[0]:[]; 
var_export($array); 

같은 출력 :

array (0 => 'reset', 1 => 'text', 2 => 'email',) 
+0

preg_match()를 사용하고 싶습니다. –

+0

이번은 현명한 선택이 아닙니다.나는 하나 만들 수는 있지만이 일에 적합한 기능이 아닙니다. 잠시만 기다려주세요. – mickmackusa

3

정규식 :/\_\K[a-zA-Z0-9]+

1\_\K_ 일치하고 \K 전체를 다시합니다 시합.

2[a-zA-Z0-9]+이 모든 문자

일치합니다

Try this code snippet here

<?php 

ini_set('display_errors', 1); 
$str = 'button_reset,location_text,email_text'; 
preg_match_all("/\_\K[a-zA-Z0-9]+/",$str,$matches); 
print_r($matches); 

출력 :

Array 
(
    [0] => Array 
     (
      [0] => reset 
      [1] => text 
      [2] => text 
     ) 
)