/    Sign up×
Community /Pin to ProfileBookmark

I want a script that can show the line if the searched word matches. For example

If I search for the words “green red” in text.txt

yellow
green
black
red
blue

then it will show the second and fourth line

Is is possible ??

to post a comment
PHP

2 Comments(s)

Copy linkTweet thisAlerts:
@saud_iqbalauthorAug 04.2005 — Can anyone give me the code. I think many users of this forum needs the same code..
Copy linkTweet thisAlerts:
@NogDogAug 05.2005 — [code=php]
<?php
function search_words_file($words, $file)
{
# note: assumes $words will be space-separated list
# read file into array of lines:
if(!is_readable($file))
{
return(FALSE);
}
$text = file($file);
# create regexp:
$search = "/";
foreach(explode(" ", $words) as $word)
{
$search .= "$word|";
}
$search = rtrim($search, "|") . "/i";
return(preg_grep($search, $text)); # returns array of matched lines
}
# test it:
$test = search_words_file("red green", "test.txt");
foreach($test as $line)
{
$line = trim($line);
echo "<p>$line</p>n";
}
?>
[/code]
×

Success!

Help @saud_iqbal spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 5.18,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @AriseFacilitySolutions09,
tipped: article
amount: 1000 SATS,

tipper: @Yussuf4331,
tipped: article
amount: 1000 SATS,

tipper: @darkwebsites540,
tipped: article
amount: 10 SATS,
)...