正则表达式和PHP - 如何匹配此字符串?

时间:2014-04-03 14:41:58

标签: php regex

我有这个字符串:

First part of string. Second part one: Second part two; Third part: Fourth part 2014. Available online:

字符串是这样制作的:

  • 字符串(点)的第一部分
  • 第二部分(冒号)
  • 第二部分二(分号)
  • 第三部分(冒号)
  • 第四部分
  • 4位数字(点)
  • 可在线获取(冒号)

如何使用正则表达式将此字符串拆分为数组?

谢谢。

3 个答案:

答案 0 :(得分:3)

您可能需要以下内容:

$array = preg_split('/\s*[:;.]\s*/', $str);

甚至:

$array = preg_split('/\s*[:;.]\s*/', $str, -1, PREG_SPLIT_NO_EMPTY);

答案 1 :(得分:-1)

$string = "First part of string. Second part one: Second part two; Third part: Fourth part 2014. Available online:";
preg_match("/(.+?)\.(.+?):(.+?);(.+?):(.+?)(\d{4})\.(.+?):/",$string,$m);
print_r($m);

输出:

Array
(
    [0] => First part of string. Second part one: Second part two; Third part: Fourth part 2014. Available online:
    [1] => First part of string
    [2] =>  Second part one
    [3] =>  Second part two
    [4] =>  Third part
    [5] =>  Fourth part 
    [6] => 2014
    [7] =>  Available online
)

希望它能帮到你。

答案 2 :(得分:-1)

使用:

([a-zA-Z ]+)\. ([a-zA-Z ]+): ([a-zA-Z ]+); ([a-zA-Z ]+): ([a-zA-Z ]+)([0-9]{4})\. ([a-zA-Z ]+):

结果:

First part of string
Second part one
Second part two
Third part
Fourth part 
2014
Available online