[英]Convert Notepad++ Regex to PHP Regular Expression
我正在嘗試將Notepad ++正則表達式轉換為PHP正則表達式,該表達式通常從URL列表中以這種格式獲取ID:
http://www.example.com/category-example/1371937-text-blah-blah-blah-2012.html
http://www.example.com/category-example/1471337-text-blah-blah-2-blah-2010.html
使用Notepad ++ regex函數,我分兩步獲得了所需的輸出(逗號分隔的ID列表)
(。*)/用空格替換
-(。*)替換為逗號
結果:1371937,1471337
我試圖用PHP preg_replace做類似的事情,但是我無法弄清楚如何獲得正確的正則表達式,下面的示例刪除了除數字之外的所有內容,但它不能按預期工作,因為可能還有不屬於ID的數字。
$bb = preg_replace('/[^0-9]+/', ',', $_POST['Text']);
?>
哪個是正確的結構?
謝謝
如果您符合以下條件:
http://www.example.com/category-example/1371937-text-blah-blah-blah-2012.html
要得到:
1371937
你會:
$url = "http://www.example.com/category-example/1371937-text-blah-blah-blah-2012.html";
preg_match( "/[^\d]+(\d+)-/", $url, $matches );
$code = $matches[1];
..匹配所有非數字字符,然后是不間斷的數字字符串,直到達到'-'
如果您只想找到ID,則應該使用preg_match
,而不是preg_replace
。
您已經迷失了該模式的選項,最簡單的是:
$url = 'http://www.example.com/category-example/1371937-text-blah-blah-blah-2012.html';
preg_match('/\d+/', $url, $matches);
echo $matches[0];
它只是在URL中找到第一串數字。 這適用於示例。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.