2011-03-05 7 views
0

두 개 이상의 탭이 뒤에 나오는 첫 번째 필드를 제외한 각 필드가 탭으로 구분 된 다음 형식의 문자열을 수정하려고합니다.preg_replace의 교체 배열에있는 특수 (이스케이프 처리 된) 문자가 이스케이프 처리됩니다.

"$str1  $str2 $str3 $str4 $str5 $str6" 

수정 된 문자열은 HTML 테이블 태그로 각 필드를 래핑하고 고유 한 들여 쓴 줄을 사용합니다.

"<tr> 
    <td class="title">$str1</td> 
    <td sorttable_customkey="$str2"></td> 
    <td sorttable_customkey="$str3"></td> 
    <td sorttable_customkey="$str4"></td> 
    <td sorttable_customkey="$str5"></td> 
    <td sorttable_customkey="$str6"></td> 
</tr> 

" 

다음과 같은 코드를 사용해 보았습니다.

$patterns = array(); 
$patterns[0]='/^/'; 
$patterns[1]='/\t\t+/'; 
$patterns[2]='/\t/'; 
$patterns[3]='/$/'; 

$replacements = array(); 
$replacements[0]='\t\t<tr>\r\n\t\t\t<td class="title">'; 
$replacements[1]='</td>\r\n\t\t\t<td sorttable_customkey="'; 
$replacements[2]='"></td>\r\n\t\t\t<td sorttable_customkey="'; 
$replacements[3]='"></td>\r\n\t\t</tr>\r\n'; 

for ($i=0; $i<count($lines); $i++) { 
    $lines[$i] = preg_replace($patterns, $replacements, $lines[$i]); 
} 

문제는 대체 배열의 이스케이프 문자 (탭과 줄 바꿈)을 대상 문자열에서 탈출 된 상태로 유지하고 나는 다음과 같은 문자열을 얻을.

$data=preg_replace("/\t+/", "\t", $data); 

나는 실종 뭔가 :

"\t\t<tr>\r\n\t\t\t<td class="title">$str</td>\r\n\t\t\t<td sorttable_customkey="$str2"></td>\r\n\t\t\t<td sorttable_customkey="$str3"></td>\r\n\t\t\t<td sorttable_customkey="$str4"></td>\r\n\t\t\t<td sorttable_customkey="$str5"></td>\r\n\t\t\t<td sorttable_customkey="$str6"></td>\r\n\t\t</tr>\r\n" 

이상하게도, 나는 에 이전 노력이 라인은 작동합니까? 어떤 생각을 고칠 수 있을까요?

+0

(예, 나는에있는 것을 알고있다 문자열이 겹치기 때문에 문자열을 약간 조정할 수 있습니다.) – Synetech

답변

1

대체 문자열에 대해 큰 따옴표 나 heredoc가 필요합니다. PCRE는 검색 문자열에서 이스케이프 문자 만 구문 분석합니다.

작업 예제에서 preg_replace("/\t+/", "\t", $data)은 이중 따옴표로되어 있기 때문에 리터럴 탭 문자입니다.

preg_replace('/\t+/', '\t', $data)으로 변경 한 경우 주 문제점이 발생할 수 있습니다. PCRE는 검색 문자열의 \t이 탭을 나타내지 만 대체 문자열의 문자는 그렇지 않다는 것을 알고 있습니다.

그래서 대체에 큰 따옴표를 사용합니다. preg_replace('/\t+/', "\t", $data), PHP는 \t을 구문 분석하고 예상 결과를 얻습니다.

약간 부정적이며 기억해야 할 부분입니다.

+0

대단히 감사합니다. (실제로, 나는 항상 큰 따옴표를 사용하며, 작은 따옴표를 사용하는 유일한 이유는 내 문자열에서 복식을 피할 필요가 없기 때문입니다. – Synetech

1

$replacements 배열의 모든 문자열은 작은 따옴표로 묶은 문자열로 표시됩니다. 즉, 이스케이프 처리 된 문자는 바뀌지 않습니다 (\' 제외).

이것은 PCRE 정규식과 직접 관련이 없으며 PHP가 문자열을 처리하는 방법과 관련이 있습니다.

기본적으로 당신은이 같은 문자열을 입력 할 수 있습니다

<?php # String test 

$value = "substitution"; 
$str1 = 'this is a $value that does not get substituted'; 
$str2 = "this is a $value that does not remember the variable"; # this is a substitution that does not remember the variable 
$str3 = "you can also type \$value = $value" # you can also type $value = substitution 
$bigstr =<<< MARKER 
you can type 
very long stuff here 
provided you end it with the single 
value MARKER you had put earlier in the beginning of a line 
just like this: 
MARKER; 

TL을, 박사 버전 : 문제가 따옴표되어야 $replacements$patterns에서 작은 따옴표입니다

관련 문제