Jump to content

Archived

This topic is now archived and is closed to further replies.

Gast

Getting characters either side of a string

Recommended Posts

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 :)

TIA

Niall

Share this post


Link to post
Share on other sites
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 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) . '...';

?>[/code]
It will print your example.

Share this post


Link to post
Share on other sites

×

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.