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!
Finding a word with x characters before and after
Moderator: General Moderators
- Grizzzzzzzzzz
- Forum Contributor
- Posts: 125
- Joined: Wed Sep 02, 2009 8:51 am
Re: Finding a word with x characters before and after
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
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
Thanks a lot, it works!