2010-08-24 34 views

回答

1

我會建議一些可能爲你工作,

// Get a file into an array. In this example we'll go through HTTP to get 
// the HTML source of a URL. 
$lines = file('http://www.example.com/'); 

// Loop through our array, show HTML source as HTML source; and line numbers too. 
foreach ($lines as $line_num => $line) { 
    // do the regular expression or sub string search here 
} 
1

據我所知,它不是,但如果你在Linux或其他類Unix系統上,grep會這樣做,並且可以使用(幾乎)與preg_函數族相同的正則表達式語法-P標誌。

1

不可以。您可以將PREG_OFFSET_CAPTURE標誌傳遞給preg_match,巫婆會告訴您以字節爲單位的偏移量。但是,沒有簡單的方法將其轉換爲行號。

+1

當你有了偏移量,你可以計算新的行數。 – 2010-08-24 20:24:29

4

有沒有簡單的方法來做到這一點,但如果你願意,你可以捕捉匹配偏移(使用PREG_OFFSET_CAPTURE標誌preg_matchpreg_match_all),然後確定用多少換行計數該行的位置是在你的字符串(例如)在該點之前發生。

例如:

$matches = array(); 
preg_match('/\bfunction\b/', $string, $matches, PREG_OFFSET_CAPTURE); 
list($capture, $offset) = $matches[0]; 
$line_number = substr_count(substr($string, 0, $offset), "\n") + 1; // 1st line would have 0 \n's, etc. 

根據什麼在你的應用程序構成了「線」,你可能會交替要搜索\r\n<br>(但是這將是一個有點棘手,因爲你必須使用另一個正則表達式來解釋<br /><br style="...">等)。

0

這不是正則表達式,但工程:

$offset = strpos($code, 'function'); 
$lines = explode("\n", substr($code, 0, $offset)); 
$the_line = count($lines); 

哎呀!這不是js!

相關問題