Jump to content

Getting characters either side of a string


Gast

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
Link to comment
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.
Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

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.