Using arrays keys without quotes, how to fix it on big project?

不打扰是莪最后的温柔 提交于 2019-12-07 15:40:01

问题


I started a project using much arrays keys without quotes.

And now I having problems with this method, i didn't knew it was bad when i started my project. I finally wanted to display E_NOTICES errors for reasons but it crash because the log is overloaded with millions notices like PHP Notice: Use of undefined constant message - assumed 'key'.

So to fix it I could add quotes to my keys in my whole project but there are so much ! Is there a way to achieve this with an algorithme or anything to fix my code ? I want replace any undefined constant by a string with quotes, EG: $my_array[key] by $my_array['key'].

Thanks.

EDIT: I succeeded to fix all declarations using rejex, like this:

\[([^0-9\$\'\"\]])([^\'\"\]]*)\] to \[\'\1\2\'\]

But it is not enough, there are much situations where unquoted keys are used without brackets, EG:

array_key_exists(unquotedKey,$array)

$array['key'] = array( unquotedKey => array(96,56) );

etc...

I could fix all situations using regex but I guess I will have much troubles to handle it well, and sometimes keys of my arrays are really constants and it shouldn't be quoted ! If anybody have a better solution it would help me a lot.

The perfect solution would be to be able to get my code after PHP replaced undefined constants by quoted strings, is it possible ? It does it each time I compile, it is maybe stored somewhere temporarily.


回答1:


I use Notepad++ which has a search and replace in files feature (Ctrl + Shift + F). With regular expression mode on, you could use

Search:

\$my_array\[([^\'\"]+)\]

Replace

\$my_array\[\'$1\'\]

The search looks for anything within the array key square brackets where there is not already a " or ' character, which would indicate the declaration is already valid.

Select the directory of your project then hit "Replace in Files". Ensure your entire project is backed up first in case something goes wrong.



来源:https://stackoverflow.com/questions/27817174/using-arrays-keys-without-quotes-how-to-fix-it-on-big-project

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!