2010-05-17 143 views
1

有沒有辦法在使用正則表達式和php時跳過第一個匹配項。如何跳過第一次正則表達式匹配?

或者有什麼方法可以使用str_replace來實現這一點。

感謝

UPDATE 我試圖刪除從另一個字符串字符串的所有實例,但我想保留第一次出現如

$toRemove = 'test'; 
$string = 'This is a test string to test to removing the word test'; 

輸出繼電器的字符串將是:

這是一個測試字符串 測試 刪除字 測試

+3

粘貼你的正則表達式和你正在使用的日期的例子。 – 2010-05-17 14:59:29

+0

是否只想匹配第一次出現或第二次出現的所有事件? – webbiedave 2010-05-17 15:00:06

+0

正則表達式:'\\ [n @。*?\\]' @webbiedave - 我想匹配除第一個外的所有事件。 – scott 2010-05-17 15:04:08

回答

3

簡單的PHP方式:

<?php 
    $pattern = "/an/i"; 
    $text = "banANA"; 
    preg_match($pattern, $text, $matches, PREG_OFFSET_CAPTURE); 
    preg_match($pattern, $text, $matches, 0, $matches[0][1]); 
    echo $matches[0]; 
?> 

會給你 「AN」。

UPDATE:不知道它是一個替換。試試這個:

<?php 
    $toRemove = 'test'; 
    $string = 'This is a test string to test to removing the word test'; 
    preg_match("/$toRemove/", $string, $matches, PREG_OFFSET_CAPTURE); 
    $newString = preg_replace("/$toRemove/", "", $string); 
    $newString = substr_replace($newString, $matches[0][0], $matches[0][1], 0); 
    echo $newString; 
?> 

找到的第一個匹配並記住它,然後刪除一切,然後把什麼是第一點回

+0

完美的作品,謝謝 – scott 2010-05-18 07:38:40

+0

呃,想到一個更聰明的方法。 <?php $ toRemove ='test'; $ string ='這是一個測試字符串來測試刪除單詞測試'; $ found = 0; echo preg_replace(「/($ toRemove)/ e」,'$ found ++?\'\':\'$ 1 \'',$ string); ?> – Amadan 2010-05-18 16:21:10

+0

完全正確。 – Amadan 2010-05-19 13:54:49

0

假設 '等等' 是你的正則表達式,等等(等等),將匹配和捕捉到的第二個

3
preg_replace('/((?:^.*?\btest\b)?.*?)\btest\b/', '$1', $string); 

的想法是匹配和捕獲任何每個匹配前,並重新插入。(?:^.*?test)?導致第一個test的實例被包含在捕獲中。 (所有\b s爲避免局部字匹配,如testsmartesttestify。)

+0

我只是愛你。 https://twitter.com/tomasdev/status/640273963688574977 - 這是將重複查詢參數轉換爲以逗號分隔的單個查詢參數的最佳方式。 – 2015-09-05 21:23:41

0

晚的答案,但它可能是有用的人。

$string = "This is a test string to test something with the word test and replacing test"; 
$replace = "test"; 
$tmp = explode($replace, $string); 
$tmp[0] .= $replace; 
$newString = implode('', $tmp); 
echo $newString; // Output: This is a test string to something with the word and replacing