Regex : preg_replace_callback과 함께 사용되는 잘못된 구문?
-
06-07-2019 - |
문제
이 링크에서 코드를 빌려 왔습니다 PHP Regex 템플릿 - {{var}}의 모든 발생을 찾으십시오. 템플릿에 값을 적용하는 수단을 구현합니다. 이것은 preg_replace_callback () 함수를 사용합니다
내가 선호하는 이름 지정 방법은 name1.name2_name3 = value보다는 name1.name2.name3 = value이지만, 내가 사용하고있는 regex에는 문제가있는 것 같습니다.
이것은 작동하지 않습니다.
템플릿 파일
.aclass{
font-width:{{newsflash.font.width}};
}
.ini 값
newsflash.font.width=8px
Regex 사용
'!\{\{(\w+).+\.\w+\}\}!'
print_r의 출력 ($ matches)
Array
(
[0] => {{newsflash.font.width}}
[1] => newsflash
)
$ matches [1]가 잘못된 키 키이기 때문에 대체가 잘못되었습니다.
.aclass{
font-width:;
}
나는 이미이 기능을 제공하고 그것에 대해 알고 싶어하는 라이브러리가 있다고 생각하지만, 여전히 Regex의 결함을 알고 싶습니다.
정규식 결함이있는 풀 코드는 다음과 같습니다.
$inputFileName = 'templateVars.css';
$outputFileName = 'templateVals.css';
$varsFileName = 'variables.ini';
$ini_array = parse_ini_file($varsFileName);
$matchesArray = array();
function replace_value($matches) {
global $ini_array;
global $matchesArray;
print "<pre>";
print_r($matches);
print "</pre>";
return $ini_array[$matches[1]];
}
$inputFileVar = file_get_contents($inputFileName);
print "<pre>";
print_r($ini_array);
print "</pre>";
print "<pre>";
print $inputFileVar;
print "</pre>";
$outFileVar = preg_replace_callback('!\{\{(\w+).+\.\w+\}\}!', 'replace_value', $inputFileVar);
print "<pre>";
print $outFileVar;
print "</pre>";
print "<pre>";
print $matchesArray;
print "</pre>";
일치 할 템플릿
.aclass{
font-width:{{newsflash.font.width}};
color:{{newsflash.font.color}}
}
.ini 파일의 내용
newsflash.font.width=8px
newsflash.font.color=red
해결책
캐릭터 .
의 일부가 아닙니다 \w
; 그리고 당신의 .+
(그룹화 파렌 외부)는 비어 있지 않은 문자열과 일치합니다 (.
와일드 카드입니다). 그러므로, $matches[1]=newsflash
맞다.
당신은 무엇을 wnat합니까 $matches[1]
되려고? 이것은 당신의 질문에서 명확하지 않습니다. 죄송합니다.
다른 팁
!\{\{(\w[\.\w]*)\}\};?!
이 regexp는 템플릿과 잘 어울리는 것 같습니다.
제휴하지 않습니다 StackOverflow