2011-11-05 100 views
0

我需要使用preg_replace或其他方式替換以'Title:'開頭並以'Article Body:'結尾的文本。替換的文字不會包含上面引用的文字。用php替換段落中的特定文本模式

如:

標題:

示例文本1

文章正文:

示例文本2

應該輸出只

示例文本2

我如何用php做到這一點?

+0

聽起來很簡單。你試過什麼了? – Gordon

+0

我知道這可以用preg_replace來完成。但我沒有正則表達式的經驗。 –

回答

0

使用積極/消極lookaheads。

$result = preg_replace('/(?<=Title:).*(?=Article Body:)/s', '\nTest\n', $subject); 

上述正則表達式將取代無論是內部標題:...文章正文:以\ NTEST \ n

說明:

" 
(?<=    # Assert that the regex below can be matched, with the match ending at this position (positive lookbehind) 
    Title:    # Match the characters 「Title:」 literally 
) 
.     # Match any single character 
    *     # Between zero and unlimited times, as many times as possible, giving back as needed (greedy) 
(?=     # Assert that the regex below can be matched, starting at this position (positive lookahead) 
    Article\ Body:  # Match the characters 「Article Body:」 literally 
) 
" 
+0

謝謝!有用。 –

0
$str = 'Title: this is sample text Article Body: this is also sample text'; 

// output: this is sample text this is also sample text 
echo preg_replace('~Title: (.*)Article Body: (.*)~', '$1 $2', $str); 

正則表達式是非常有用的,你應該學會如何使用它。網上有很多文章,也可以幫助你。

+0

謝謝!但是這不起作用。我需要將這個模式替換爲沒有文字。 –

+0

@AmilaPremasiri:從第二個參數中刪除'$ 2'。 – hakre

+0

它是否與字符串文字一起作爲替換參數('$ 1 $ 2''位)?我一直認爲必須是非文字字符串(例如'「$ 1 $ 2」')。 – CD001