Qbasicnews.com

Full Version: highlighting in PHP
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Pages: 1 2
Im VERY new to PHP (started today :lol: ) and need some help. I want to show a file and highlight a certain word that is entered.

I have a form with 2 text boxes. you enter the name of the file that you want open and the word you want highlighted. those are sent to "search.php" with POST.

Ive managed to show the file that is requested with
<?php require($_POST['filename']; ?> //filename is the textbox name
and that works fine.
Now, how would I parse that file highlighting $_POST['keyword'] ?
str_replace could be the function you need. You can also use ereg_replace/preg_replace, if you need regular expression matching (like "any letter five times then two ciffers" and the like).

load the file into a variable:
Code:
$file_original = implode("",file($_POST['filename']));

"file" returns the file requested as an array, with each index containing one line. "implode" gathers them into one line. There is another function that does the same more clear, but I can't remember the name.

Highlighting:
Code:
$find = $search_word;
$highlighted = '<b>' . $search_word . '</b>';

$file_passed = str_replace($find,$highlighted,$file_original);

well... showing:
Code:
echo $file_passed;
Thanx for that info zap. It was easy to implement. There is still a problem though....
What Im supposed to do is load a text file to the screen
Code:
<HTML>
<HEAD>
<TITLE>
Index.php
</TITLE>
<BODY>

<form action="getfile.php" method="post">               <!--form with POST action
Enter a file to view: <input type="text" name="filename" />    <!--name of file (filename)
<input type="submit" value=" Load File " />            <!--Submib button
</form>


</BODY>
</HTML>
Is the code ive used to do this. it (obviously) loads the file using the post method in getfile.php.
Code:
<HTML>
<HEAD>
<TITLE>
getfile.php
</TITLE>
<BODY>

<?php
   $file_original=implode("",file($_POST['filename'])); /*got original file in 1 line array*/
   echo $file_original;                    /*so lets put it on screen*/
?>


<HR WIDTH=95%>

<form action="getfile.php" method="post">
Find Keyword: <input type="text" name="keyword" />
<input type="submit" value=" Find " />
</form>


</BODY>
</HTML>
Now you notice the text box at the bottom of the loaded file (called 'keyword'). I have to put a keyword in and submit the page to itself!!! if I could submit it to another page i wouldnt have a problem. the error is when i resubmit the page, $_POST['filename'] brings an error. i assume its cause it now dosnt have a correct value when the page is reloaded. Im ment to resubmitted the page, highlighting the word put into the textbox.
with what you're doing, you have to resend the original file WITH the new keyword variable.

i would get the filename and word to highlight at once.

Code:
<HTML><HEAD><TITLE> Index.php </TITLE><BODY><?
if ($filename) {
  $file_original=implode("",file($_POST['filename']));
## and the highlight code and display the parsed file here
}
?>

<form action="getfile.php" method="post">
<BR>Enter a file to view: <input type="text" name="filename" value="<?=$filename; ?>" />
<BR>Find Keyword: <input type="text" name="keyword" />
<BR><input type="submit" value=" Load File " />
</form>

</BODY></HTML>

and that's untested.

just make sure that the file and the keyword are both present.
Yeah that would be the problem. Each time you reload the page, a new instance of it is loaded on the server, and therefore no variables are kept.

If you don't want the filename to show, you can have it in a hidden field instead of a textbox. But that's really a detail:

Code:
<input type="hidden" name="filename" value="<?=$filename; ?>
Notice how the type is "hidden". It won't show on the page, but the variable will be sent anyway.

Also, the implode function doesn't make it a one-line array, but a simple string, instead of an array where each index contains a line from the file. Just thought I should tell you.

Lastly, if you use potatos code, you wont need to files as you did before. Just change the

Code:
if ($filename) {
line to
Code:
if ($_POST['filename']) {

So you won't run into strange stuff.
Lovely! It works just like I want! I used the "hidden" trick for something else as well. Im keen to put some stats on the page aswell. I got how many matches are found, that was easy using substr_count(). It wouldnt let me use the optional count argument in str_replace, which would have been nice. I want to shown how long it took to show the page. I tried using getmicrotime() but it returned an error?

The last thing(I hope) that I plan on adding is case insensitivity. if the user enters "QuickBasic" it must highlight "quickbasic","Quickbasic","QUICKBASIC" etc....
the function str_ireplace() is ment for that I think, but its only in PHP5.
php4 version of str_ireplace, from php.net: (just paste it into the bottom of your script, inclosed by <? and ?> ofcause.)

Code:
function stri_replace($find,$replace,$string)
{
       if(!is_array($find)) $find = array($find);
       if(!is_array($replace))
       {
               if(!is_array($find)) $replace = array($replace);
               else
               {
                       // this will duplicate the string into an array the size of $find
                       $c = count($find);
                       $rString = $replace;
                       unset($replace);
                       for ($i = 0; $i < $c; $i++)
                       {
                               $replace[$i] = $rString;
                       }
               }
       }
       foreach($find as $fKey => $fItem)
       {
               $between = explode(strtolower($fItem),strtolower($string));
               $pos = 0;
               foreach($between as $bKey => $bItem)
               {
                       $between[$bKey] = substr($string,$pos,strlen($bItem));
                       $pos += strlen($bItem) + strlen($fItem);
               }
               $string = implode($replace[$fKey],$between);
       }
       return($string);
}

Example of use, also from php.net:

Code:
$foobar = 'FoO FOO foo bAr BAR bar';
echo stri_replace(array('foo','bar'),'woggle',$foobar);

// echos 'woggle woggle woggle woggle woggle woggle'

There is no build in function called "getmicrotime", it's microtime(). The example from php.net uses it in a home brewn function called getmicrotime:
Code:
function getmicrotime()
{
   list($usec, $sec) = explode(" ", microtime());
   return ((float)$usec + (float)$sec);
}

$time_start = getmicrotime();
  
for ($i=0; $i < 1000; $i++) {
   // do nothing, 1000 times
}

$time_end = getmicrotime();
$time = $time_end - $time_start;

echo "Did nothing in $time seconds\n";

Put your stuff instead of the "for" loop.
If you want to highlight a file, use the highlight_file(filename) function.

You may have to run it through htmlentities as well, but I'm not sure about that.
I just downloaded the manual. It has those functions in it(as you said Big Grin ) I didnt use stri_replace() but used eregi_replace. Im rewriting the code using a neater style and was wondering if stri_replace would do the same thing as eregi_replace? If the user searched for "QUICKBASIC" the hightlighted word would be "QUICKBASIC" even if the original word was "QuickBasic" (I think i explained that okay??). is there a way around this? which function is the better one?

Also, using substr_count wouldnt count the words that were a different case to the search word.

eg
Code:
"This is a example"
eregi_replace() will highlight  'is' in 'Th'is'' and 'is'
but the count will be 0 if the user enters 'IS' as the search word
This is because substr_count is case sensitive right? is there a insensitive version?

I know that this questions are a bit vague, but im sure they're understandable.
Sorry bout all the n00b questions, but the manual is on another computer and my time online is limited.
Quote:If you want to highlight a file, use the highlight_file(filename) function.

But that highligths php syntax, and that's not what he wants.



Quote:This is because substr_count is case sensitive right? is there a insensitive version?

Yes correct. No. But it's very easy to do anyway:

Code:
substr_count(strtolower($search_in), strtolower($search_for))

It will pass the lowercase version of search_in and search_for, without changing the real text at all.

Quote:If the user searched for "QUICKBASIC" the hightlighted word would be "QUICKBASIC" even if the original word was "QuickBasic" (I think i explained that okay??). is there a way around this? which function is the better one?

It can be done with eregi_replace, like this:

Code:
$pattern = '('. quotemeta($_POST['keyword']) .')';
$replacement = '<b>\\1</b>';
$file_passed = eregi_replace($pattern, $replacement, $file_original);

'\\1' refers to whatever it finds using teh first part (enclosed by parenthesis (sp?) ) in $pattern.
Pages: 1 2