2010-03-23 50 views
7

我使用它使用如何將eregi轉換爲preg_match?

eregi($match="^http/[0-9]+\\.[0-9]+[ \t]+([0-9]+)[ \t]*(.*)\$",$line,$matches) 

一個lib但eregi現在已經過時了,我想上述轉換成的preg_match。我試了一下,如下

preg_match($match="/^http/[0-9]+\\.[0-9]+[ \t]+([0-9]+)[ \t]*(.*)\$/i",$line,$matches) 

但它拋出一個錯誤說Unknown modifier '[' in filename.php

任何想法如何解決這個問題?

感謝

+0

良好的文檔,你可以離開了'$匹配='在這兩個代碼例子,這樣他們是完全不必要的 – lamas 2010-03-23 16:08:24

+0

[「如何將PHP的eregi更改爲preg_match」](http://customphpfunctions.blogspot.com/2011/12/how-to-change-phps-eregi-to-pregmatch.html )解釋了eregi和preg_match,以及如何替換折舊函數。 – 2011-12-04 19:39:22

回答

6

如果使用/作爲正則表達式分隔符(即preg_match('/.../i', ...)),則需要在您的模式中轉義任何/的實例,否則php會認爲它指的是模式的結尾。

您也可以使用不同的字符,如%作爲分隔符:

preg_match('%^http/[0-9]+\.[0-9]+[ \t]+([0-9]+)[ \t]*(.*)$%i',$line,$matches) 
+0

。是的,當PHP在正則表達式中找到任何'/'時,它會認爲是正則表達式的結尾。 – 2011-07-08 13:29:34

6

你需要躲避正則表達式內delimiters(在這種情況下/):

"/^http\\/[0-9]+\\.[0-9]+[ \t]+([0-9]+)[ \t]*(.*)\$/i" 

但你也可以選擇不同的分隔符像~

"~^http/[0-9]+\\.[0-9]+[ \t]+([0-9]+)[ \t]*(.*)\$~i" 
+0

第一個建議就像一個魅力。用於'/'解釋的+ 1 + – 2011-12-06 23:59:39

5

你可以試試:

preg_match("@^http/[0-9]+\\.[0-9]+[ \t]+([0-9]+)[ \t]*(.*)\[email protected]",$line,$matches) 
  • 您可以刪除的$match=
  • 您正在使用/作爲分隔符 並且存在另一個/存在於 http之後的正則表達式,它實際上是 標誌着你的正則表達式的結束。當PHP 看到[後,它抱怨。
  • 您可以使用一組不同的 分隔符爲@或逃避/http