Hello, 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!
+1
A:
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.
zerkms
2010-06-07 13:50:54
A:
<?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.
Wrikken
2010-06-07 13:56:12
A normal `grep` command from the command line usually way faster BTW, but of course less portable.
Wrikken
2010-06-07 13:58:07