php find line number for a particular keyword
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.
精彩评论