3

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.

sylvain1264
  • 855
  • 2
  • 8
  • 23

2 Answers2

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.

Ian
  • 590
  • 2
  • 19
  • Thanks I never used this before, it's very useful ! I finally did it like this: \$(.*)\[(.*)\] by \$\1\[\'\2\'\] – sylvain1264 Jan 07 '15 at 10:48
  • Please note my edit - the regex pattern you used would not have accounted for already valid declarations. The edit accounts for this. – Ian Jan 07 '15 at 10:54
  • Ok I could fix my code with this but finally I'm still looking for a better solution (note my edit). – sylvain1264 Jan 08 '15 at 07:12
  • I answered the question you asked. Now you have amended the question you shouldn't unmark this answer as correct, you should ask a new question as the specification has changed – Ian Jan 09 '15 at 09:29
  • Ok sure, sorry I'm new and not used to the system ! I believed it was better to do it this way. – sylvain1264 Jan 09 '15 at 16:06
0

Use this pattern

[a-zA-Z0-9]{1,}(\[([^'"$0-9]+)\])

to find array keys without quotes like this:

$_POST[content_id]