Jump to content


Photo

Getting characters either side of a string


  • Please log in to reply
1 reply to this topic

#1 Gast

Gast
  • Members
  • PipPipPip
  • Advanced Member
  • 131 posts
  • LocationSouth East England

Posted 29 May 2006 - 07:38 PM

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 strpos(). I want to t..."

If that makes sense. I have tried using substr but it didnt really work :)

TIA

Niall
OS and Internet Specs:
Windows XP (with SP2), 1680x1050, PHP 4, MySQL 3, Internet Explorer 6 &7 /FireFox 2.0/Opera 9.2

Tutorials:
Simple Introduction to AJAX and XMLHttpRequest
Creating Live Data with AJAX Making a Google Suggest like application

#2 poirot

poirot
  • Members
  • PipPipPip
  • Advanced Member
  • 646 posts
  • LocationAustin, TX

Posted 29 May 2006 - 08:05 PM

I think this may help:
<?php

// part_of_string( string string, string needle [, int pad ] )
// pad means number of chars after and before the needle
function 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) . '...';

?>
It will print your example.
~ D Kuang




0 user(s) are reading this topic

0 members, 0 guests, 0 anonymous users