开发者

php find line number for a particular keyword

开发者 https://www.devze.com 2023-01-03 02:12 出处:网络
say I have a paragraph of text, with some new lines/line breaks. I would like to find the occurance of a certain keyword, and开发者_如何学编程 return the line numbers of those keywords. How do I do th

say I have a paragraph of text, with some new lines/line breaks. I would like to find the occurance of a certain keyword, and开发者_如何学编程 return the line numbers of those keywords. How do I do that? Thanks!


you can use substr_count() in a manner like:

$line_number = substr_count($str, "\n", 0, strpos($str, 'keyword')) + 1;

where $str is the source string.


<?php
$string="
foo keyword bar
foobar
foobar
foo keyword bar
keyword
keyword";
var_dump(preg_grep('/keyword/',explode("\n",$string)));
?>

outputs:

array(4) {
  [1]=>
  string(15) "foo keyword bar"
  [4]=>
  string(15) "foo keyword bar"
  [5]=>
  string(7) "keyword"
  [6]=>
  string(7) "keyword"
}

So you could just do an array_keys on that if you like.

0

精彩评论

暂无评论...
验证码 换一张
取 消