Reputation: 85
I'm learning PHP and built a little search in text file script. Here is the chain of events:
My issue is that:
If I have a sentence like:
Tom has a camera in his hand. I am also a camera on the floor.
And search for "am", it searches and finds camera, replaces this with the span class. Then it finds "am" and replaces it within Camera twice, and itself.
Here is my code:
//---- Puts Array into or responds with error
$lines = file($filename, FILE_IGNORE_NEW_LINES);
if ( !is_array($lines) ) {
echo 'Cannot create array from file';
}
//---- Scans and Displays Lines
$submission = $_GET['Search'];
function scanLines($lines, $submission) {
foreach($lines as $line) {
if(strpos($line,$submission)!== false){
preg_match_all("/\b[a-z]*".preg_quote($submission)."[a-z]*\b/i", $line, $matches);
$i = 0;
foreach($matches[$i] as $match) {
$line = str_replace($match, '<span class="highlight">'.$match.'</span>', $line);
$i++;
}
echo $line;
}
}
}
Direct link to example: http://www.effectivemark.com/testphp/
My question is: What is the best approach to filter out the "am" in camera, so it doesn't add the string with span tag like below:
<span class="highlight">c<span class="highlight">am</span>era</span>
Updated code:
//---- Scans and Displays Lines
$submission = $_GET['Search'];
function scanLines($lines, $submission) {
foreach($lines as $line) {
if(strpos($line,$submission)!== false){
$words = explode(' ', $line);
$i = 0;
$combine = array();
foreach($words as $word) {
if (preg_match("/\b[a-z]*".preg_quote($submission)."[a-z]*\b/i", $word)) {
preg_match_all("/\b[a-z]*".preg_quote($submission)."[a-z]*\b/i", $word, $match);
$matches = '<span class="highlight">' . $match[0][0] . '</span>';
}
else {
$matches = $word;
}
array_push($combine, $matches);
$i++;
}
foreach($combine as $combined) {
echo $combined . ' ';
}
}
}
}
Upvotes: 0
Views: 848
Reputation: 11328
I think this would be ok:
<form action="" method="post">
<h4>Search Object In Text File:</h4>
<input type="text" name="search" value="">
<input type="submit" value="Submit" name="Submit">
</form>
<?php
$filename="tekst.txt";
$lines = file($filename, FILE_IGNORE_NEW_LINES);
if ( !is_array($lines) ) {
echo 'Cannot create array from file';
}
//---- Scans and Displays Lines
if(isset($_POST['search']))
$submission = $_POST['search'];
scanLines($lines,$submission);
function scanLines($lines, $submission) {
foreach($lines as $line) {
$word_arr=str_word_count($line,1);
$length=count($word_arr);
for($i=0;$i<$length;$i++) {
if(preg_match("#$submission#",$word_arr[$i],$match)) {
$word_arr[$i]='<span class="highlight">'.$word_arr[$i].'</span>';
$new_line=implode(' ',$word_arr);
echo $new_line.'<br>';
}
}
}
}
?>
So, if you want to search FOR ANY PART OF THE WORD, and highlight whole word, rather than just matched part. For complete (more rigid) whole word search, you can just use simple in_array() function.
Upvotes: 0