sublimetext3text-editor

Find keyword to limit within a method/function only not the whole file with sublime or other text editor


Good day,

I am using sublime text editor, is there a way to find a keyword within a specific function/method only?

for example, in my controller User.php, there are multiple functions inside it, now I want to search for a variable '$user_id ' inside the function save() only.. so that if I need to find next, I wouldnt accidentally edit the same variable on my delete() function. this would be useful if the code inside a function long .. any idea or recommendation ? thanks!

function save(){
    
    $user_id = '';
    .......
    .......
    $user_id=0;

}

function delete(){
    
    $user_id = '';
    .........

}

function view(){
    $user_id = 1;

    .........

}

Solution

  • Here is a regex that does the job:

    (?:function save\h*\(.*?\)\h*{\R|\G)(?:(?!function)[\s\S])+?\K\$user_id
    

    Explanation:

    (?:                     # non capture group
        function save           # literally
        \h*                     # 0 or more horizontal spaces
        \(.*?\)                 # arguments of the function
        \h*                     # 0 or more horizontal spaces
        {                       # literally
        \R                      # any kind of linebreak
      |                       # OR
        \G                      # restart from last match position
    )                       # end group
    (?:                     # non capture group
        (?!function)            # next word must not be "function"
        [\s\S]                  # any character 
    )+?                     # end group, must appear 1 or more times, not greedy
    \K                      # forget all we have seen until this position
    \$user_id               # expression to be searched
    

    Demo & Explanation