2011-02-02 65 views
0

我正在通過PHP Curl提取ASP/VBScript配置文件來完成某些文件處理並希望返回一些值。需要正則表達式來匹配不同格式的名稱/值對

琴絃看起來像這樣:

config1 = "" 
config2 = "VALUE:1:0:9" 'strange value comment 
otherconfig = False 
yetanotherconfig = False 'some comment 

基本上,它的名稱值對由等號分離,用任選內引號包圍的值任選地隨後進行評論。

我想回到實際值(false,值:1:0:9,等等)。在

無論格式字符串中的一個匹配的組下面是我傳遞模式到目前爲止的preg_match:

$pattern = '/\s*'.$configname.'\s*\=\s*(\".*?\"|.*?\r)/' 

$配置名稱是具體的配置我正在尋找的名字,所以我通過它與一個變量。

我仍然得到括號中包含的值(而不是值本身),並且我也收到了與該值一起返回的註釋。

任何幫助表示讚賞!

+0

我沒有看到你的配置樣本中的任何括號。 – BoltClock 2011-02-02 17:14:40

+0

對不起!引號..! – tresstylez 2011-02-02 17:17:39

回答

1

如果由於雙引號備選方式的困難而返回一個匹配組中的匹配值。回去參考可以幫助:

$pattern = '/\s*'.$configname.'\s*=\s*("?)(?<value>.*?)\1\s*[\'$]/' 

應該做的伎倆。然後使用$result['value']

解釋在英語中它的作用:

  • 我跳過空間標識符空間=空間(容易)
  • 可以匹配"如\ 1(第一個捕獲括號)
  • 匹配任何字符引用不貪婪地引用爲value
  • 匹配\ 1(所以"如果有一個之前,或者什麼,如果不是)
  • 可搭配一些作者

    $pattern = '/\s*'.$configname.'\s*=\s*(?:"(.*?)"|(.*?)\s*[\'$])/' 
    

    更有效,但其值在$result[1]$result[2]:百步

  • 必須一開始註釋'或線

的末端沒有反向引用匹配。

瞭解你的錯誤:

  • 需要\只保護字符串引號本身(這裏簡單引號)或避免浸漬炭保留被解釋(爲.^$ ...)線
  • 最終被標記爲$,不是\ R或\ n
  • 你永遠不迴避評論
0

\ r要匹配一個CR字符(回車)。 你基本上說我想匹配「???????」或???????? [回車]

當然,你會得到撇號,你已經匹配它。 你必須去掉這些東西。

patter ='/\s*'.$configname.'\s*\=\s*(\")(.*?)((()(")\"*)\s*/'

0

這一個將工作:

$pattern = '/ 
    \s* 
    # name 
    (?P<name>.*?) 
    # = 
    \s*=\s* 
    # value 
    (?P<val> 
     "(?P<quoted>([^"]|\\\\"|\\\\\\\\)*)" 
     |(?P<raw>.*?) 
    ) 
    # comment 
    \s*(?P<comment>\'.*)? 
$/xm'; 

這將在輸入字符串中的每個鍵=值對匹配,而不是僅僅一個特定的一個。

正則表達式處理引號中的引號和引號(\")(例如"foo\"bar")。

具有這樣的功能使用它:

function parse_config($string) { 
    $pattern = '/ 
     \s* 
     # name 
     (?P<name>.*?) 
     # = 
     \s*=\s* 
     # value 
     (?P<val> 
      "(?P<quoted>([^"]|\\\\"|\\\\\\\\)*)" 
      |(?P<raw>.*?) 
     ) 
     # comment 
     \s*(?P<comment>\'.*)? 
    $/xm'; 

    preg_match_all($pattern, $string, $matches, PREG_SET_ORDER); 

    $config = array(); 
    foreach($matches as $match) { 
     $name = $match['name']; 
     if (!empty($match['quoted'])) { 
      $value = str_replace(array('\\"','\\\\'), array('"','\\'), $match['quoted']); 
     } else if (isset($match['raw'])) { 
      $value = $match['raw']; 
     } else { 
      $value = ''; 
     } 
     $config[$name] = $value; 
    } 

    return $config; 
} 

例子:

$string = "a = b\n 
c=\"d\\\"e\\\\fgh\" ' comment"; 

$config = parse_config($string); 

// output: 

array('a' => 'b', 'c' => 'd"e\fgh'); 

其他例如:

$string = <<<EOF 
config1 = "" 
config2 = "VALUE:1:0:9" 'strange value comment 
otherconfig = False 
yetanotherconfig = False 'some comment 
EOF; 

print_r(parse_config($string)); 

// output: 

Array 
(
    [config1] => 
    [config2] => VALUE:1:0:9 
    [otherconfig] => False 
    [yetanotherconfig] => False 
)