2016-02-25 260 views
1

我有一個字符串,它是一個包含下面的代碼片段一個PHP代碼示例:替換字符串正則表達式

$data = array(
    'cKey1' => "dsfaasdfasdfasdfasdf", 
    'cKey2' => "asdfasdfasdfadsfasdf", 
    ... 
); 

目前我只是做了str_replace兩個硬編碼的鑰匙,但我需要這現在變得更加靈活。這是兩個正則表達式,我拿出這麼遠:

(?<=cKey1' =>).+(?=,) 
(?<=cKey2' =>).+(?=,) 

但是,由於一些人不使用空格,使用雙引號,等等,這不是一個理想的解決方案。有人能以更好的方式指出我以更有效的方式取代cKey1cKey2的值嗎?

謝謝!

+1

使用的分詞器。 http://php.net/manual/en/function.token-get-all.php –

+0

@anubhava:輸出將是相同的原始字符串,只是具有由值(類似於上面的例子中),而不是real cKeys –

回答

1

您可以使用\K(匹配復位功能):

$re = array("/'cKey1'\s*=>\s*\K[^,]*/", "/'cKey2'\s*=>\s*\K[^,]*/"); 

$repl = array('"foo"', '"bar"') 

echo preg_replace($re, $repl, $str); 

輸出:

$data = array(
    'cKey1' => "foo", 
    'cKey2' => "bar", 
    ... 
); 
+0

這幾乎爲我做了。我使用'file_get_contents()'獲得了代碼示例的內容,但是我失去了一些開始行(可能由於<?php')。如果我在file_get_contents()周圍使用'htmlspecialchars()',那麼數據仍然是完美的,但是您的解決方案不會取代。有關於此的任何想法? –

+0

'串(478)「, 」2e73625b5179497a423434736e「, 'cKey2'=> 」036289E99EA6A48CBDA1DB247E「, '文件'=> 'V2/API /車博士/ exampleAPI2.0.1.php');'可以看到它切斷開始標記和'$ data = array(' –

+0

'cat -vte V2/api/autoDoc/test.php <?php $ ^ I $ data = array($ ^ I^I'cKey1'=>「2e73625b5179497a423434736e」, $ ^ I^I'cKey2'=>「036289E99EA6A48CBDA1DB247E」,$ ^ I^I'file'=>'V2/api/autoDoc/exampleAPI2.0.1.php'$ ^ I); $ ^ I $ ' –

1

或者使用標記生成器像@Casimir說或者(如果你堅持使用正則表達式),你能想出某事。像下面這樣:

$regex = "~ 
      'cKey\d+'   # search for cKey followed by a digit 
      .+?     # match everything lazily 
      ([\"'])    # up to a single/double quote (capture this) 
      (?P<string>.*?)  # match everything up to $1 
      \1     # followed by the previously captured group 
     ~x"; 
preg_match_all($regex, $your_string, $matches); 

如果你想與某事來取代它,可以考慮使用preg_replace_callback(),雖然你不是你的預期輸出清晰。
參見a demo on regex101.com。感謝@WiktorStribiżew在評論中的澄清。

+0

當您將邊界定義爲雙引號或單引號時,您應該依賴惰性點匹配,而不是取反的字符類。另外'(\「|')'=>'([\」'])' –

+0

@WiktorStribiżew:我重視您的意見,所以你會這麼好的說爲什麼用偷懶點會是在這種情況下更好? – Jan

+0

與[' 'cKey1'=> 「dsfaasdfasdfasd'fasdf」,'](https://regex101.com/r/fX2sL8/1)輸入檢查正則表達式。 –