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 Link to comment https://forums.phpfreaks.com/topic/10726-getting-characters-either-side-of-a-string/ 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. Link to comment https://forums.phpfreaks.com/topic/10726-getting-characters-either-side-of-a-string/#findComment-40060 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.