带有特殊字符的正则表达式

I have this code from which I like to return an array that holds all hits for patterns that starts with 'some' and ends with 'string'.

$mystr = "this string contains some variables such as  $this->lang->line('some_string') and $this->lang->line('some_other_string')";
preg_match_all ("/\bsome[\w%+\/-]+?string\b/", $mystr, $result);

However I like to have all hits that starts with

$this->lang->line('

and ends with

')

Furthermore, I need to have the start and end patterns left out. In other words, I like to see 'some_string' and 'some_other_string' in my resulting array. Replacing 'some' and 'string' straight forward is not working, because of special characters?

Here an example that escapes the special chars for you:

$mystr = "this string contains some variables such as \$this->lang->line('some_string') and \$this->lang->line('some_other_string')";
#array of regEx special chars
$regexSpecials = explode(' ',". ^ $ * + - ? ( ) [ ] { } \\ |");

#test string 1
#here we have the problem that we have $ and ', so if we use
# single-quotes we have to handle the single-quote in the string right.
# double-quotes we have to handle the dollar-sign in the string right.
$some = "\$this->lang->line('";

#test string 2
$string = "')";

#escape   chr(92) means \ 
foreach($regexSpecials as $chr){
   $some = str_replace($chr,chr(92).ltrim($chr,chr(92)),$some);
   $string = str_replace($chr,chr(92).ltrim($chr,chr(92)),$string);
}

#match 
preg_match_all ('/'.$some.'(.*?)'.$string.'/', $mystr, $result);

#show
print_r($result);

The hard part is to escape everthing right in php and in the regexstring.

  • You have to escape the dollar sign in php right when used in double-quotes
  • Also you have escape all special characters right for the regex.

Read more here:

What special characters must be escaped in regular expressions?

What does it mean to escape a string?

$mystr = "this string contains some variables such as  $this->lang->line('some_string') and $this->lang->line('some_other_string')";

preg_match_all("/\$this->lang->line\('(.*?)'\)/", $mystr, $result);

Output:

array(1
    0   =>  array(2
                0   =>  $this->lang->line('some_string')
                1   =>  $this->lang->line('some_other_string')
            )
    1   =>  array(2
                0   =>  some_string
                1   =>  some_other_string
            )

)