【问题标题】:Using preg_match and str replace to find a word and highlight it使用 preg_match 和 str replace 查找单词并突出显示
【发布时间】:2012-08-07 23:25:40
【问题描述】:

这是我的代码..

<?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 中使用什么模式?谢谢。

【问题讨论】:

  • 第 21 个单词在索引 20,而不是 22
  • 那么您能确定正在加载的页面实际上只是一个单词列表,还是其中有其他内容?如果是这样,您的explode 将受到威胁。此外,数组的第 21 个键是 $arr[20],而不是 21(因为 0 是第一个)。
  • 这可能会有所帮助:stackoverflow.com/questions/9304212/…
  • 我不明白为什么你需要正则表达式来查找单词,当你已经分解了单词数组并且只需要在 index = 20 处访问单词
  • 如果要过滤掉html标签,拜托拜托,拜托forget about regex,只解析文档!

标签: php preg-match str-replace


【解决方案1】:

这里的问题是您引用的页面将返回站点的 HTML 内容...所以它不会是第 21 个人类可读的单词...但是您可以通过以下方式突出显示它!我不确定 str_replace 中 $words[20] 的双重声明,但它有效。有人会插话纠正...

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

【讨论】:

  • 不完全——str_replace 的参数是搜索、替换、主题,所以它需要是str_replace($words[20],'text',$words[20])
  • 对于某些函数,参数的顺序可以不同。例如。 here 您会发现“由于历史原因,implode() 可以按任意顺序接受其参数。但是,为了与 explode() 保持一致,使用文档中的参数顺序可能不会造成混淆。”找不到相同的 str_replace,但可能是相同的原因。
猜你喜欢
  • 2019-03-15
  • 2015-10-14
  • 1970-01-01
  • 1970-01-01
  • 2014-08-07
  • 1970-01-01
  • 1970-01-01
  • 2013-06-29
  • 1970-01-01
相关资源
最近更新 更多