Gast Posted May 29, 2006 Share Posted May 29, 2006 I have matched a string inside another using strpos(). I want to then get 15 or so characters from both the left and right of the string, so if I was matching the word "strpos" in this sentence it would produce the following:"... another using [b]strpos[/b](). I want to t..."If that makes sense. I have tried using substr but it didnt really work :)TIANiall Quote Link to comment Share on other sites More sharing options...
poirot Posted May 29, 2006 Share Posted May 29, 2006 I think this may help:[code]<?php// part_of_string( string string, string needle [, int pad ] )// pad means number of chars after and before the needlefunction part_of_string($str, $needle, $pad=15){ $pos = strpos($str, $needle); if (!$pos) { $ret = false; } else { $start = ($pos - $pad > 0) ? $pos - $pad : 0; $end = $pos + strlen($needle) + $pad; $length = ($end > strlen($str)) ? strlen($str)-$start : $end-$start; $ret = substr($str, $start, $length); } return $ret;}$string = 'I have matched a string inside another using strpos(). I want to then get 15 or so characters from both the left and right of the string, so if I was matching the word "strpos" in this sentence it would produce the following:';$needle = 'strpos';echo '...' . part_of_string($string, $needle) . '...';?>[/code]It will print your example. Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.