是否有可能有一個正則表達式搜索像'\ bfunction \ b'這樣的字符串,它將顯示找到匹配的行號?在PHP中使用正則表達式時可以顯示行號嗎?
2
A
回答
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,巫婆會告訴您以字節爲單位的偏移量。但是,沒有簡單的方法將其轉換爲行號。
4
有沒有簡單的方法來做到這一點,但如果你願意,你可以捕捉匹配偏移(使用PREG_OFFSET_CAPTURE
標誌preg_match
或preg_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!
相關問題
- 1. 你可以在.babelrc中使用正則表達式嗎?
- 2. 我可以在DynamoDB查詢中使用正則表達式嗎?
- 3. 在HTML解析中可以使用正則表達式嗎?
- 4. 你可以在CSS img [alt = *]中使用正則表達式嗎?
- 5. 我們可以在web.xml中使用正則表達式嗎?
- 6. 我可以在C#中使用String.Replace的正則表達式嗎?
- 7. 可以在Protege OWL查詢中使用正則表達式嗎?
- 8. 你可以在struts-config.xml中使用正則表達式嗎?
- 9. 我可以在正則表達式中使用求和嗎?
- 10. 我可以在datetime.strptime格式內使用正則表達式嗎?
- 11. MySQL可以在UPDATE中進行正則表達式替換嗎?
- 12. 如何在正則表達式中顯示負號和加號
- 13. 我可以使用XPath表達式中的正則表達式
- 14. 在php中使用正則表達式
- 15. 在PHP中使用正則表達式
- 16. PL/SQL函數中可以使用正則表達式嗎?
- 17. 正則表達式顯示
- 18. 正則表達式行顯示jsHint
- 19. 正則表達式中的#符號php
- 20. 是否可以在正則表達式中使用組而不顯示結果?
- 21. 是它可以使用正則表達式使用PHP
- 22. 使用正則表達式以正則表達式
- 23. 在PHP中正則表達式中轉義引號時出錯
- 24. 正則表達式可以使用不同的語言嗎?
- 25. 可以使用交集縮短此正則表達式嗎?
- 26. 我可以使用帶有guard-concat的正則表達式嗎?
- 27. 我可以使用正則表達式的字符編碼嗎?
- 28. 我可以使用正則表達式嗎?
- 29. 正則表達式「行號」中的Acme
- 30. 只顯示使用正則表達式的YouTube網址+ php
當你有了偏移量,你可以計算新的行數。 – 2010-08-24 20:24:29