我正在尝试查找字符串内的PHP变量的所有情况。
所有PHP变量都以$字符开头,因此我基本上是在双引号字符串中搜索该字符。
我希望我的正则表达式也可以用于多行字符串。
到目前为止,我有这个:
"[^"]*?\$[\w\d]+[^"]*?"
但是在这种情况下:
"a string" with no $variable in it
"a single line string with a $variable in it"
在第一行中,匹配$ variables末尾的最后一个报价。显然,如果正则表达式仅应在引号内搜索此字符。
任何帮助,将不胜感激。
谢谢
最佳答案
一种简单的方法是使用tokenizer:
$source = <<<'EOD'
<?php // <-- needed
$data = 'Sed pulvinar metus $eget';
echo "tellus euismod tristique. $Nullam vitae";
if ($data === "mi id risus {$pretium['porttitor']} $vitae a lorem.")
// Aenean laoreet $urna eu erat laoreet, sit amet pretium purus consequat.
/* print "Curabitur $iaculis augue eget arcu dapibus"; */
echo <<<DATA
Duis id $mauris at ante ornare eleifend at sed magna
DATA;
EOD;
$tokens = token_get_all($source);
$flag = false;
$result = array();
foreach ($tokens as $token) {
if ($token =='"')
$flag = ! $flag;
elseif ($flag && is_array($token) && $token[0] == T_VARIABLE)
$result[] = $token[1];
}
print_r($result);
确实,也可以使用正则表达式模式来完成。但是,该模式将比您想象的要复杂,因为您需要跳过:注释,简单引号中的字符串,heredoc,nowdoc,双引号中没有变量的字符串。为了给您一个想法,请看关于php注释的this post。
注意:您也可以轻松地更改此代码以处理heredoc语法(或您想要的任何内容)
关于php - 正则表达式在字符串中查找PHP变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23182769/