Jump to content

How do I... (PHP. Searching Functions?)


d22552000

Recommended Posts

Are there any PHP functions or language varients that will search a variable or string for a certain string?  and that will return where it was found or even just a search that will return if it was found or not...

 

I was wondering this, trying to make a search engine for my site.  There was no PHP search function.. -,-.  Anyone know what I gotta do?

Link to comment
https://forums.phpfreaks.com/topic/69836-how-do-i-php-searching-functions/
Share on other sites

But what exactly would it give me... would it return the byteface of the found string?

 

oh and BTW "strrchr — Find the last occurrence of a character in a string" completely useless to me, only searches a character at a time.  Thanks for hte first two links though.

 

PHP FTW!

<?PHP

function search($mystring='abcaaab',$findme='a',$debug=1) {

   $res[0] = strpos($mystring, $findme); $r=0;
   $len=strlen($mystring); $result=1;

   while ($r!=$len) {$result++; $r++;
       $res[$result] = strpos($mystring, $findme, $pos);
       $pos=$res[$result]+1; $res[$result]=$res[$result]+1;

       if ($res[$result]==$len-1) {
           break;
           }
       }

   $result.=" Results";

   if ($res[0] === false) {
       echo "Your search criteria returned no results.<br /><br />";
       if ($debug=1) {
           echo "Debug: '\$findme'='$findme'; '\$mystring'='$mystring'";
           }
       } else {
       echo "Your search returned $result:<br /><br />";
       if ($debug=1) {
           echo "Debug: '\$findme'='$findme'; '\$mystring'='$mystring'<br />";
           }
       foreach ($res as $value) {
           echo "<br /> $value";
           }
       }
   unset($l); unset($len); unset($res); unset($value); unset($result);
   }

?>

 

This is the code im using now as my search class.

I have one problem... How would I detect the end of results to end my while?

 

I tried calling my function with:

 

search('This is a sentance','a');

The output is

Your search returned 19 Results:

Debug: '$findme'='a'; '$mystring'='This is a sentance'

8
9
15
1
9
15
1
9
15
1
9
15
1
9
15
1
9
15
1

 

But it returns the results about 5 times before exiting. How would I detect the end of the string has been reached?

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.