문제

PHP 스타일 변수가 포함된 일반 텍스트(PHP 코드 아님)를 가져와 변수 값으로 대체하는 가장 좋은 방법은 무엇입니까?이건 설명하기가 좀 어렵네요. 예를 들어보겠습니다.

// -- myFile.txt --
Mary had a little $pet.

// -- parser.php --
$pet = "lamb";
// open myFile.txt and transform it such that...
$newContents = "Mary had a little lamb.";

나는 정규 표현식을 사용하는 것을 고려하고 있습니다. eval(), 하지만 어느 것이 가장 쉬울지는 잘 모르겠습니다.이 스크립트는 로컬에서만 실행되므로 보안 문제 및 eval() 적용하지 않는다 (제 생각에는?).

또한 다음을 사용하여 필요한 모든 변수를 배열로 가져올 수 있다는 점을 추가하겠습니다. get_defined_vars():

$allVars = get_defined_vars();
echo $pet;             // "lamb"
echo $allVars['pet'];  // "lamb"
도움이 되었습니까?

해결책

신뢰할 수있는 소스에서 나온 경우 사용할 수 있습니다 (극적인 일시 정지) 평가 () (청중의 공포의 헐떡 거림).

$text = 'this is a $test'; // single quotes to simulate getting it from a file
$test = 'banana';
$text = eval('return "' . addslashes($text) . '";');
echo $text; // this is a banana

다른 팁

Regex는 충분히 쉬울 것입니다. 그리고 그것은 그 일에 신경 쓰지 않을 것입니다 eval() 구문 오류를 고려합니다.

PHP 스타일 변수 이름을 찾는 패턴은 다음과 같습니다.

\$\w+

아마도이 일반적인 패턴을 가져 와서 PHP 배열을 사용하여 내가 찾은 각 경기를 찾아보십시오 (사용preg_replace_callback()). 이렇게하면 정규식을 한 번만 적용해야하며 장기적으로 더 빠릅니다.

$allVars = get_defined_vars();
$file = file_get_contents('myFile.txt');

// unsure if you have to use single or double backslashes here for PHP to understand
preg_replace_callback ('/\$(\w+)/', "find_replacements", $file);

// replace callback function
function find_replacements($match)
{
  global $allVars;
  if (array_key_exists($match[1], $allVars))
    return $allVars[$match[1]];
  else
    return $match[0];
}

방금 생각해낸 내용은 다음과 같습니다. 하지만 더 좋은 방법이 있는지 알고 싶습니다.건배.

$allVars = get_defined_vars();
$file = file_get_contents('myFile.txt');

foreach ($allVars as $var => $val) {
    $file = preg_replace("@\\$" . $var . "([^a-zA-Z_0-9\x7f-\xff]|$)@", $val . "\\1", $file);
}

PET가되어야합니까? 될 수 있습니다 <?= $pet ?> 대신에? 그렇다면 사용하기 만하면 포함하십시오. 이것은 템플릿 엔진으로서 PHP의 전체 아이디어입니다.

//myFile.txt
Mary had a little <?= $pet ?>.

//parser.php

$pet = "lamb";
ob_start();
include("myFile.txt");
$contents = ob_end_clean();

echo $contents;

이것은 반향됩니다.

Mary had a little lamb.

상황에 따라 str_replace 트릭을 할 수 있습니다.

예시:

// -- myFile.txt --
Mary had a little %pet%.

// -- parser.php --
$pet = "lamb";
$fileName = myFile.txt

$currentContents = file_get_contents($fileName);

$newContents = str_replace('%pet%', $pet, $currentContents);

// $newContents == 'Mary had a little lamb.'

str_replace를 살펴보면 검색 및 교체 매개 변수를 검색하고 교체하기 위해 값의 배열을 가져갈 수 있습니다.

당신은 사용할 수 있습니다 strtr:

$text = file_get_contents('/path/to/myFile.txt'); // "Mary had a little $pet."
$allVars = get_defined_vars(); // array('pet' => 'lamb');
$translate = array();

foreach ($allVars as $key => $value) {
    $translate['$' . $key] = $value; // prepend '$' to vars to match text
}

// translate is now array('$pet' => 'lamb');

$text = strtr($text, $translate);

echo $text; // "Mary had a little lamb."

get_defined_vars ()에서 선불을하고 싶을 것이므로 변수를 두 번 루프하지 않습니다. 또는 더 나은 방법은 MyFile.txt에서 사용하는 식별자와 처음에 할당하는 키를 확인하십시오.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top