2012-08-07 34 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

相关问题