PHP中的正则表达式:从另一个字符串中检索特定字符串

时间:2018-09-15 11:16:05

标签: php regex

我想从字符串中提取一些单词。

The 24,000th eligible entrant will win. This giveaway started September 14,  
2018 3:35 PM PDT and ends the earlier of September 21, 2018 11:59 PM PDT or  
when the prize has been awarded.

我想提取的单词是:

  • 第24,000位
  • 2018年9月14日下午3:35
  • 2018年9月21日晚上11:59

我尝试使用以下内容:

$regex = "[\d,]+th|\w+[\d\s,:]+PM";

if (preg_match($regex, $str, $match)) {
    echo $match[0];
}

2 个答案:

答案 0 :(得分:1)

您可以尝试

/[\d,]+th|September[\d\s,:]+PM/

如果月份在变化

/[\d,]+th|\w+[\d\s,:]+PM/

在您的代码中:

$regex = "/[\d,]+th|\w+[\d\s,:]+PM/"

if (preg_match_all($regex, $str, $match))
    echo $match[0]

;

有关说明,请参见链接

demo here

答案 1 :(得分:0)

您需要在正则表达式中添加定界符,并使用preg_match_all

$str = "The 24,000th eligible entrant will win. This giveaway started September 14, 2018 3:35 PM PDT and ends the earlier of September 21, 2018 11:59 PM PDT or when the prize has been awarded.";
$regex = "/[\d,]+th|\w+[\d\s,:]+PM/";

if (preg_match_all($regex, $str, $match))
    print_r($match[0]);

输出:

Array
(
    [0] => 24,000th
    [1] => September 14, 2018 3:35 PM
    [2] => September 21, 2018 11:59 PM
)