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

时间:2017-03-28 09:06:24

标签: php preg-match-all

我有这个代码,我想从中返回一个数组,该数组包含以' some'开头的模式的所有匹配。以'字符串'结尾。

$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);

但是我喜欢所有以

开头的点击
$this->lang->line('

结束
')

此外,我需要省略开始和结束模式。换句话说,我喜欢看到#some_string'和' some_other_string'在我的结果数组中。替换一些'和'字符串'由于特殊字符,直接进行是不行的?

1 个答案:

答案 0 :(得分:0)

这是一个逃避特殊字符的例子:

$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);

困难的部分是在php和regexstring中逃避纠正。

  • 在双引号
  • 中使用时,你必须在php中转义美元符号
  • 此外,您还可以使用正则表达式转义所有特殊字符。

在这里阅读更多内容:

What special characters must be escaped in regular expressions?

What does it mean to escape a string?