2017-03-28 250 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 
      ) 

)