phpregexvisual-studio-codecode-snippetsregexp-replace

VSCODE snippet PHP to fill namespace automatically


I'm trying to create a VSCODE CODE SNIPPET for PHP that automatically put the namespace (based on folder path).

The idea is make a substitution on the directory of the current document, considering that all my class are located inside the MVC folder, and that this is located inside the src folder, examples:

I got the full folder name with VSCODE snippet variabe $TM_DIRECTORY.

Aparently hasn't error on REGEX, as you can see on: https://regex101.com/r/P8CpkX/1

My try of the snipped code:

"namep": {
        "prefix": [
            "namep"
        ],
        "body": [
            "",
            "// TM_DIRECTORY: $TM_DIRECTORY",

            "namespace ${TM_DIRECTORY/.*src\/(([^\/]*)(\/)?)|(\/)([^\/]*)/$2\\$5/g};"
        ],
        "scope": "php",
        "description": "Try to put namespace automatically"
    }

It results in:

// TM_DIRECTORY: /home/user/dev/project/src/MVC/Models/Access/Auth
namespace ${TM_DIRECTORY/.*src/(([^/]*)(/)?)|(/)([^/]*)/$5/g};

But the expected is (as demonstrated on REGEX):

// TM_DIRECTORY: /home/user/dev/project/src/MVC/Models/Access/Auth
namespace \MVC\Models\Access\Auth;

Could anyone helps to fix it?

Thanks a lot!!!


Solution

  • You can use

    "namep": {
        "prefix": [
            "namep"
        ],
        "body": [
            "namespace \\\\${TM_DIRECTORY/(?:.*[\\/\\\\])?src[\\/\\\\]([^\\/\\\\]*)[\\/\\\\]?|[\\/\\\\]([^\\/\\\\]*)/$1\\$2/g}",
        ],
        "scope": "php",
        "description": "Try to put namespace automatically"
    }
    

    See the regex demo.

    It matches

    Demo:

    enter image description here