SimaPro
SimaPro

Reputation: 1234

PHP: Preg_Match, trying to return a certain number of characters ahead of match

I am trying to match a certain string - then return, lets say 3 characters before and after that string. How would I do that? Here is my current code:

<?php
$data = file_get_contents('all.htm');
$regex = '/span/';
preg_match($regex,$data,$match);?>
<pre>
<?php var_dump($match);?>
</pre>

And that returns:

array(1) {
  [0]=>
  string(4) "span"
}

Upvotes: 1

Views: 498

Answers (1)

nhahtdh
nhahtdh

Reputation: 56809

This will match up to 3 characters before and after a specified string (here is "span")

/(.{0,3})span(.{0,3})/

You can pick up the adjacent characters from the match array.

Upvotes: 3

Related Questions