基本上,我需要一个正则表达式来匹配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...';如果能够在脚本标记too...but中匹配到一个正则表达式替换,那将是一件很棒的事情。
我需要一种正则表达式方法,而不是PHP方法。假设我在文本编辑器或JavaScript中使用regex-replace来清理PHP源代码。
发布于 2015-02-10 01:40:34
tl;dr
这实在是太复杂了,用正则表达式无法完成。尤其不是一个简单的正则表达式。使用嵌套正则表达式可能会更好,但是确实需要使用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...忘记双引号字符串中的匹配变量名。你能只匹配这个例子中的所有字符串吗?对我来说就像是噩梦。因此,语法突出显示肯定不知道如何处理它。
您是否考虑过变量也可能出现在heredoc字符串中?
我不想考虑正则表达式来检查是否:
<?php or <?= codeH115前面是否有\ (escaped)?
\ escaped??摘要
您也许可以为此编写一个正则表达式。你也许可以通过一些反向引用和大量的时间和细心来管理。这将是困难的,您可能会浪费很多时间,如果您需要修复它,您将不会理解您编写的正则表达式。
另请参阅
This answer。这是值得的。
发布于 2013-07-11 17:30:03
下面是一个函数,它利用标记器扩展将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;作为第一个参数传递的正则表达式是这里的关键。它告诉函数,如果字符串不包含$ (embedded variable "$a"__)、{ (embedded variable Type2 "{$a[0]}"__)、换行符、<或> (HTML标签结束/开始符号),则仅将字符串转换为单引号的等价物。它还检查字符串是否包含单引号,并防止替换,以避免需要转义的情况。
虽然这是一个PHP解决方案,但它是最准确的解决方案。与任何其他语言最接近的情况是,您需要在某种程度上使用该语言构建自己的PHP解析器,以便您的解决方案更加准确。
https://stackoverflow.com/questions/17589150
复制相似问题