2012-08-07 62 views
0

這是我的代碼..使用的preg_match和STR更換,以找到一個詞,並強調它

<?php 
    // first get all the html contents 

    $page = file_get_contents('http://www.planetled.com.au/blog/what-is-a-led-spotlight/'); 


    //next explode it 
    $words = explode(" ", $page); 

    // then display the 21st word or any word you like 
    echo $words[22]; // 21st word 
?> 

下一個我想要的是找到21人可讀字。我正在考慮用preg_match找到這個詞,然後使用str_replace,但是我缺少的是我會在preg_match中使用哪個模式?謝謝。

+1

21字的索引爲20,而不是22 – rsplak 2012-08-07 14:27:26

+0

那麼你可以肯定在加載該頁面是從字面上只是一個單詞的列表,或者是有其他的內容那裏?如果是這樣,你的'爆炸'將受到影響。此外,數組的第21個鍵是'$ arr [20]',而不是21(因爲0是第一個)。 – Utkanos 2012-08-07 14:27:41

+0

這可能有助於:http://stackoverflow.com/questions/9304212/sed-replacing-nth-word-with-matched-pattern – mlishn 2012-08-07 14:28:05

回答

1

這裏的問題是你所引用的頁面將返回該網站的HTML內容......所以它不會是第21個人類可讀的詞......但這裏是你如何突出顯示它!我不確定str_replace內的$ words [20]的雙重聲明,但它有效。有人會附和修正...

str_replace($words[20], "<span style='background-color:yellow'>$words[20]</span>", $words[20]); 
+1

不完全 - str_replace的參數是搜索,替換,主題,所以它需要'str_replace($ words [20],'text',$ words [20])' – weltschmerz 2012-08-07 14:53:11

+0

謝謝,編輯。爲什麼我的例子工作? – 2012-08-07 14:54:12

+0

http://codepad.viper-7.com/uFMnEQ – 2012-08-07 15:00:25

相關問題