Sandbox Home  |  OmegaSoft Homepage  |  Products & Services  |  About OmegaSoft


 


Code Libraries


Projects & Resources

Find if a string exists within a string

This function checks to see if a string exists within a string.

It will return TRUE or FALSE depending on the result.

Example

<?php

// Find if a string contains a URL
echo instr("This is content visit http://localhost for more""http://"false);

// Returns TRUE

?>

<?php

/**
* This function sees if a string exists within a string
*
* @access private
* @return boolean TRUE if found, FALSE if not found
* @param string $string Haystack
* @param string $find needle
* @param boolean $case_sensitive TRUE if searching casse sensitively, FALSE for otherwise
*/
function instr($string$find$case_sensitive false

    
$i 0;
    
    
// Loop through each character within the string
    
while (strlen($string) >= $i
    { 
        unset(
$substring); 
        if (
$case_sensitive
        { 
            
$findstrtolower($find); 
            
$string strtolower($string); 
        }
        
        
$substring substr($string$istrlen($find));
        
        
// Found the needle
        
if ($substring == $find)
        {
            return 
true
        }
        
        
// Next
        
$i++; 
    } 
    
    return 
false
}

?>



Developer Comments

Haig Evans-Kavaldjian
Why not just use (boolean) strpos() instead. This should be MUCH faster than your instr() function.


Ian
It would be nice if you could supply an array as the needle for multiple words.


Your name
Email address
Comments
 


© Copyright 2008  |  Terms of Use  |  OmegaSoft Homepage  |  Feedback