Page 1 of 1

Finding a word with x characters before and after

Posted: Wed Feb 24, 2010 4:04 am
by Ruben
Hello everyone,

I've been trying to figure this out for a while though but no luck so far. First I'd like to find a word in a string, then I'd like to put x characters in front of this word in a new string, the word itself, and then y characters behind the word.

$str = "The quick brown fox jumped over the lazy dog.";
$search = "fox";

*some function with x=3 and y=6*

Should result in:

$newstring = "wn fox jumpe";

I think that this can be done with Regular Expressions?

Thanks for you help!

Re: Finding a word with x characters before and after

Posted: Wed Feb 24, 2010 5:27 am
by Grizzzzzzzzzz
here's something simple and scabby to get your ideas rolling

Code: Select all

 
    $str = "The quick brown fox jumped over the lazy dog.";
    $search = "fox";
    $begins = strpos($str, $search);
    
    $x = 3;
    $y = 6;
    
    $limit = $begins + $y + strlen($search);
    $begins -= $x;
    
    while($begins != $limit){
        echo $str[$begins];
        $begins++;
    }
 

Re: Finding a word with x characters before and after

Posted: Wed Feb 24, 2010 6:08 am
by Apollo
regexp FTW:

Code: Select all

function FunkySearch( $needle, $haystack, $before, $after )
{
  return preg_match("/.{"."$before}$needle.{"."$after}/",$haystack,$m) ? $m[0] : false;
}
 
$str = "The quick brown fox jumped over the lazy dog.";
$search = "fox";
print(FunkySearch($search,$str,3,6)); // gives 'wn fox jumpe'

Re: Finding a word with x characters before and after

Posted: Wed Feb 24, 2010 7:22 am
by Ruben
Thanks a lot, it works!