[英]Regex to match double quoted strings without variables inside php tags
基本上我需要一個正則表達式來匹配PHP標簽內的所有雙引號字符串,而不包含變量。
這是我到目前為止所擁有的:
"([^\$\n\r]*?)"(?![\w ]*')
並替換為:
'$1'
但是,這也會匹配PHP標記之外的內容,例如HTML屬性。
示例案例:
<a href="somelink" attribute="value">Here's my "dog's website"</a>
<?php
$somevar = "someval";
$somevar2 = "someval's got a quote inside";
?>
<?php
$somevar3 = "someval with a $var inside";
$somevar4 = "someval " . $var . 'with concatenated' . $variables . "inside";
$somevar5 = "this php tag doesn't close, as it's the end of the file...";
它應該匹配並替換"
應該用'
替換'
所有地方,這意味着理想情況下應該保留html屬性。
替換后的輸出示例:
<a href="somelink" attribute="value">Here's my "dog's website"</a>
<?php
$somevar = 'someval';
$somevar2 = 'someval\'s got a quote inside';
?>
<?php
$somevar3 = "someval with a $var inside";
$somevar4 = 'someval ' . $var . 'with concatenated' . $variables . 'inside';
$somevar5 = 'this php tag doesn\'t close, as it\'s the end of the file...';
能夠匹配內部腳本標簽也很棒......但是這可能會推動它進行一次正則表達式替換。
我需要一個正則表達式方法,而不是PHP方法。 假設我在文本編輯器或JavaScript中使用regex-replace來清理PHP源代碼。
對於正則表達式來說,這實在是太復雜了。 特別是不是一個簡單的正則表達式。 你可能有更好的運氣嵌套正則表達式,但你真的需要lex / parse來找到你的字符串, 然后你可以使用正則表達式對它們進行操作。
你也許可以設法做到這一點。 你可以甚至可能設法做好這一點,甚至完美 。 但這並不容易。 這將非常困難。
考慮一下:
Welcome to my php file. We're not "in" yet.
<?php
/* Ok. now we're "in" php. */
echo "this is \"stringa\"";
$string = 'this is \"stringb\"';
echo "$string";
echo "\$string";
echo "this is still ?> php.";
/* This is also still ?> php. */
?> We're back <?="out"?> of php. <?php
// Here we are again, "in" php.
echo <<<STRING
How do "you" want to \""deal"\" with this STRING;
STRING;
echo <<<'STRING'
Apparently this is \\"Nowdoc\\". I've never used it.
STRING;
echo "And what about \\" . "this? Was that a tricky '\"' to catch?";
// etc...
忘記在雙引號字符串中匹配變量名。 你可以匹配這個例子中的所有字符串嗎? 對我來說,這看起來像是一場噩夢。 SO的語法突出顯然肯定不知道如何處理它。
您是否認為變量可能也出現在heredoc字符串中?
我不想考慮正則表達式檢查是否:
<?php
或<?=
代碼中 \\
(轉義)? \\
逃脫? 你可以為此寫一個正則表達式。 你可以用一些反向引用和大量的時間和關心來管理。 它會很難,你可能會浪費很多時間,如果你需要修復它 ,你就不會理解你寫的正則表達式了。
這個答案 。 這很值得。
這是一個利用tokenizer擴展僅將preg_replace
應用於PHP字符串的函數:
function preg_replace_php_string($pattern, $replacement, $source) {
$replaced = '';
foreach (token_get_all($source) as $token) {
if (is_string($token)){
$replaced .= $token;
continue;
}
list($id, $text) = $token;
if ($id === T_CONSTANT_ENCAPSED_STRING) {
$replaced .= preg_replace($pattern, $replacement, $text);
} else {
$replaced .= $text;
}
}
return $replaced;
}
為了達到你想要的效果,你可以這樣稱呼它:
<?php
$filepath = "script.php";
$file = file_get_contents($filepath);
$replaced = preg_replace_php_string('/^"([^$\{\n<>\']+?)"$/', '\'$1\'', $file);
echo $replaced;
作為第一個參數傳遞的正則表達式是此處的鍵。 它告訴函數只將字符串轉換為單引號等價物,如果它們不包含$
(嵌入變量"$a"
) , {
(嵌入變量類型2 "{$a[0]}"
) ,新行, <
或>
(HTML標記結束/打開符號)。 它還檢查字符串是否包含單引號,並防止替換以避免需要轉義的情況。
雖然這是一個PHP解決方案,但它是最准確的。 您可以使用任何其他語言獲得的最接近的語言要求您在某種程度上使用該語言構建自己的PHP解析器,以使您的解決方案准確無誤。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.