-3

I have a project with many array() key without quotes

$ary = array( name => "Smith" ); 

Any way to convert its key with quote?

$ary = array( 'name' => "Smith" ); 

I know codes like

$ary[name] = "Smith" ; // can change to $ary['name'] using editor with regexp 

But the problem if it is coded this way

$ary = array( name => "Smith" ); // or worse $ary = array( name => "Smith", class => "2A" ); 

How to use regexp to add quote to the array key?

This project has thousands of php files. Any body had experience this and what do you recommend to search and replace all php files. Thank you.

4
  • 1
    show some actual fragment of that code(keys without quotes) Commented Aug 17, 2016 at 6:27
  • how did you have thousands of invalid files to start with ?!? Commented Aug 17, 2016 at 6:38
  • Why do you want to change that? Commented Aug 17, 2016 at 6:40
  • @Dagon it happens when error_reporting value was set to hide notices and above for a long time. I dealt myself with this kind of stuff when I lifted this setting. I suppose the OP has the similar case Commented Aug 17, 2016 at 7:38

2 Answers 2

2

You should use a text editor which supports find and replace option using a REGEX.

Refer to this: How to fix associative array keys that lack single quotation marks in multiple files

Sign up to request clarification or add additional context in comments.

1 Comment

It looks like that answer fixes only the $ary[name] = "Smith" ; stuff but not the other variations
0

You will need two regexp passes with find/replace

The first one that replaces $ary[name] = "Smith" is listed here.

Match: (\$[a-zA-Z0-9]+\[)([^\]]+)\]

Replace: \1'\2']

https://regex101.com/r/aJ3cN9/1

The second one targets the name => "Smith" case:

Match: ([a-zA-Z0-9]+)\s*=>

Replace: '\1' =>

https://regex101.com/r/wH9cC5/1

To mass replace this you can use vim as described here, any mature PHP IDE like NuSphere or PhpStorm or many Text editors (Notepad++ or SublimeText) - just check the menu "Search" in them. Be sure the files you are modifying are under the version control so that you can rollback any changes that you don't want.

Also if you keys may include underscores use [a-zA-Z0-9_] instead of [a-zA-Z0-9] in both regexps.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.