Luis
Luis

Reputation: 67

php regex everything before and after year

I have this string which has a year in the middle. I want to extract the year and everything before and after it.

I'm using the following individual regexes:

  1. extract date: '/\d{4}\b/'
  2. extract everything before date: '/(.*?)\d{4}\b/'; (i don't know how to exclude date from the result but that's not a problem...)
  3. extract everything after date: '/d{4}\/(.*?)\b/' (this one is not working)

Upvotes: 0

Views: 476

Answers (1)

zamnuts
zamnuts

Reputation: 9592

$str = 'The year is 2048, and there are flying forks.';
$regex = '/(.*)\b\d{4}\b(.*)/';
preg_match($regex,$str,$matches);

$before = isset($matches[1])?$matches[1]:'';
$after = isset($matches[2])?$matches[2]:'';

echo $before.$after;

Edit: To answer OP's (Luis') comment on having multiple years:

$str = 'The year is 2048 and there are 4096 flying forks from 1999.';
$regex = '/(\b\d{4}\b)/';
$split = preg_split($regex,$str,-1,PREG_SPLIT_DELIM_CAPTURE);
print_r($split);

$split provides an array like:

Array
(
    [0] => The year is 
    [1] => 2048
    [2] =>  and there are 
    [3] => 4096
    [4] =>  flying forks from 
    [5] => 1999
    [6] => .
)

This secondary example also shows the risk involved with assumptions on parsable data (note the number of forks at 4096 matches that of a 4-digit year).

Upvotes: 5

Related Questions