我正在尝试匹配某些缺少前导美元符号的 PHP 代码中的变量,以此作为修复代码的方法。
样本输入:
foo = "bar"
$bar = foo
foo()
$foo = bar;
bar = foo() {}
$foo = array();
应该匹配:
foo = "bar" -> match foo not bar
$bar = foo -> match foo not bar
foo() -> no match
$foo = bar; -> match bar not foo
bar = foo() {} -> match bar not foo
$foo = array(); -> no match
它应该匹配所有未被引用的词
[A-Za-z0-9_]
,并且不以$
开头或以(
结尾。
编辑:
一个小例子来更好地解释我想要实现的目标:
<?php
/**
* little script to explain better what im trying to achieve
*/
echo "\nSay Hi :P\n=========\n\n";
$reply = null;
while ("exit" != $reply) {
// command
echo "> ";
// get input
$reply = trim( fgets(STDIN) );
// last char
$last = substr( $reply, -1 );
// add semicolon if missing
if ( $last != ";" && $last != "}" ) {
$reply .= ";";
}
/*
* awesome regex that should add $ chars to words
* to make using this more comfortable!
*/
// output buffer
ob_start();
eval( $reply );
echo $out = ob_get_clean();
// add break
if ( strlen( $out ) > 0 ) {
echo "\n";
}
}
echo "\n\nBye Bye! :D\n\n";
?>
这个表达实际上符合你的例子。
/(?<![$'"])\b([a-z_]+)\b(?!['"(])/i
您将很难尝试使用正则表达式解析编程语言。当您开始获得更复杂的表达式时,正则表达式将变得不够用。
尽管如此,这里有一个匹配您所有示例的正则表达式:
(?<![^\s])\w+(?![^;\s])
您可以扩展它以满足您的需求。