php regex前后一切

Lui*_*uis 0 php regex

我有这个字符串,中间有一年.我想提取年份和之前和之后的所有内容.

我正在使用以下单个正则表达式:

  1. 提取日期: '/\d{4}\b/'
  2. 在日期之前提取所有内容:( '/(.*?)\d{4}\b/';我不知道如何从结果中排除日期,但这不是问题......)
  3. 在日期之后提取所有东西:( '/d{4}\/(.*?)\b/'这个不起作用)

zam*_*uts 5

$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;
Run Code Online (Sandbox Code Playgroud)

编辑:回答OP(Luis')关于多年的评论:

$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);
Run Code Online (Sandbox Code Playgroud)

$split 提供如下数组:

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

此次要示例还显示了对可解析数据的假设所涉及的风险(请注意,4096处的货叉数量与4位数年份的数量相匹配).