Finding a word with x characters before and after

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
Ruben
Forum Newbie
Posts: 2
Joined: Wed Feb 24, 2010 3:55 am

Finding a word with x characters before and after

Post 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!
User avatar
Grizzzzzzzzzz
Forum Contributor
Posts: 125
Joined: Wed Sep 02, 2009 8:51 am

Re: Finding a word with x characters before and after

Post 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++;
    }
 
User avatar
Apollo
Forum Regular
Posts: 794
Joined: Wed Apr 30, 2008 2:34 am

Re: Finding a word with x characters before and after

Post 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'
Ruben
Forum Newbie
Posts: 2
Joined: Wed Feb 24, 2010 3:55 am

Re: Finding a word with x characters before and after

Post by Ruben »

Thanks a lot, it works!
Post Reply