2017-03-28 196 views
0

我有这个代码,我喜欢返回一个数组,它包含所有匹配模式,以'some'开始并以'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); 

但是我喜欢与

$this->lang->line(' 

启动所有安打,而且与

') 

结束,我需要有冷落的开始和结束模式。换句话说,我喜欢在我的结果数组中看到'some_string'和'some_other_string'。由于特殊字符,直接替换'some'和'string'是行不通的?

+0

什么[strpos(http://php.net/manual/en/function.strpos.php)?如果您找到该位置,请查找结束标签并将所有内容都放在中间。 – Peon

+0

下次访问https://regex101.com/并在发布问题前尝试自行解决。尝试是最好的学习方式。这是一个非常基本的问题,你确切知道你需要在两者之间进行搜索。 – mickmackusa

+0

不是基本的我。感谢您的链接,我会练习。 – user3104427

回答

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?

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

输出:

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 
      ) 

)