2014-01-27 36 views
0

我有一個要從句子開頭刪除的單詞列表。如何從句子開頭刪除單詞列表

有了這個代碼,我能夠從字符串的開頭只刪除1個字,在這個例子中,單詞「你好」

for($i=0; $i<strlen(string); $i++){ 
    $remove = 'Hello'; 
    if (substr(string, 0, strlen($remove)) == $remove) { 
    string = substr(string, strlen($remove));} 
    string=ucfirst(string);} 

input :Hello World. 
output:World. 

如何修改這個代碼,並添加單詞列表使用刪除代碼一次?也許一連串的話會很棒。

也無法使用這個代碼幾次,每個單詞,我必須刪除,但在性能方面,我認爲會變慢。任何幫助?謝謝

回答

0

嘗試使用PHP preg_replace函數。

$string = 'Hello world Hello'; 

$patterns = array(); 
$patterns[0] = '/Hello/'; 

$replacements = array(); 
$replacements[0] = ''; 

ksort($patterns); 
ksort($replacements); 

echo preg_replace($patterns, $replacements, $string, 1); 

參考:http://www.php.net/manual/en/function.preg-replace.php

+0

我想刪除句子的第一個單詞。 – mwweb

+0

我已經更新了答案。請你能這樣。 – Duli

0

我會爆炸串入的陣列。

$string = 'these are words some of which may be bad like this1 this2 and this3'; 

$words = explode(' ', $string); 

foreach($words as $word) { 

    // Insert function to check your list of words against an array remove 
    // and even replace them with your own. 
    // View: preg_replace http://us2.php.net/manual/en/function.preg-replace.php 

} 
相關問題