如何在 PHP 中动态替换符号之间的文本并替换为常量


How to dynamically replace text between symbols and replace with a constant in PHP?

我有一个问题,我需要搜索 HTML 页面/片段并替换任何介于四个百分位数符号之间的值并转换为常量变量,例如 %%THIS_CONSTANT%% 变为THIS_CONSTANT。

现在我正在逐行搜索页面,我能够找到匹配项并使用preg_match_all和preg_replace替换它们。

$file_scan = fopen($directory.$file, "r");    
if ($file_scan) {                                     
  while (($line = fgets($file_scan)) !== false) {
    if(preg_match_all('/'%%(.*?)'%%/', $line, $matches)){
      foreach($matches as $match){
        foreach($match as $m){
          $repair = preg_replace('/'%%(.*?)'%%/', $m, $m);
          if(preg_match('/'%%(.*?)'%%/', $m, $m)){
          } else {
            echo $repair.' '.$j;
            $j++;
          }
        }
        $lines[$i] = preg_replace('/'%%(.*?)'%%/', constant($repair), $line);
      }
    } else {
      $lines[$i] = $line;    
    }
    $i++; 
  }
  $template[$name] = implode("", $lines);
  fclose($file_scan);
}

此代码无法做的是在一行上查找和替换多个匹配项。例如,如果有一行包含:

<img src="%%LOGO_IMAGE%%"><h1>%%TITLE%%</h1>

上面的代码将用相同的值(TITLE)替换这两个项目。它还会使错误在第一个循环中找不到常量,但在第二个循环中可以正常工作。

这种情况很少发生,但我只是想知道如何在一行上修改多个实例以确保安全。

编辑:

我能够用这个替换大部分代码:

$file_scan = fopen($directory.$file, "r");
if ($file_scan) {
  while (($line = fgets($file_scan)) !== false) {
    $line = preg_replace('/'%%(.*?)'%%/', '$2'.'$1', $line);
    echo $line;
  }             
fclose($file_scan);

我的最后一个问题是将替换的项目更改为常量。这可能吗?

最终编辑:

在Peter Bowers建议的帮助下,我使用preg_replace_callback添加了将关键字更改为常量的功能:

foreach($filenames as $file){
  $name = str_replace('.html', '', $file);
  $template[$name] = preg_replace_callback('/'%%(.*?)'%%/', function($matches){                 
    $matches[0] = preg_replace('/'%%(.*?)'%%/', '$1', $matches[0]);
    return constant($matches[0]);
   }, file_get_contents($directory.$file));
  }
return $template;

这是一个更简单的实现。

$file_scan = fopen($directory.$file, "r");    
if ($file_scan) {                                     
  $out = '';
  while (($line = fgets($file_scan)) !== false) {
    $out .= preg_replace('/'%%(.*?)'%%/', '$1', $line);
    $i++; 
  }
  $template[$name] = $out;
  fclose($file_scan);
}

或者,更简单:

$str = file_get_contents($directory.$file);
$template[$name] = preg_replace('/'%%(.*?)'%%/', '$1', $str);

而且,由于我们在这里非常简单...

$template[$name] = preg_replace('/'%%(.*?)'%%/', '$1', file_get_contents($directory.$file));

(显然,当我们接近单行时,您正在失去一些错误检查功能,但是 - 嘿 - 我玩得很开心...... :-)

试试这个:

<?php
define('TITLE', 'Title');
define('LOGO_IMAGE', 'Image');
$lines = array();
$file_scan = fopen($directory.$file, "r");    
if ($file_scan) {                                     
  while (($line = fgets($file_scan)) !== false) {
    if(preg_match_all('/'%%(.*?)'%%/', $line, $matches)){
      for($i = 0; $i < count($matches[0]); $i++) {
          $line = str_replace($matches[0][$i], constant($matches[1][$i]), $line);
     }
     $lines[] = $line; 
     print_r($line);
   }
 }
}    
$template[$name] = implode("", $lines);
fclose($file_scan);
?>