Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/272.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
PHP preg_match_all/正则表达式问题_Php_Regex_Preg Match All - Fatal编程技术网

PHP preg_match_all/正则表达式问题

PHP preg_match_all/正则表达式问题,php,regex,preg-match-all,Php,Regex,Preg Match All,我有一个文本字符串,如下所示: 2012-02-19-00-00-00+136571235812571+UserABC.log 我需要将其分成三段数据:第一个+2012-02-19-00-00-00左边的字符串,两个+136571235812571之间的字符串和+UserABC.log右边的字符串 我目前有以下代码: preg_match_all('\+(.*?)\+', $text, $match); 我遇到的问题是上面的代码返回:+136571235812571+ 有没有一种方法可以使用

我有一个文本字符串,如下所示:

2012-02-19-00-00-00+136571235812571+UserABC.log
我需要将其分成三段数据:第一个+2012-02-19-00-00-00左边的字符串,两个+136571235812571之间的字符串和+UserABC.log右边的字符串

我目前有以下代码:

preg_match_all('\+(.*?)\+', $text, $match);
我遇到的问题是上面的代码返回:+136571235812571+

有没有一种方法可以使用正则表达式给我所有三个数据段而不带+标记,或者我需要一种不同的方法


谢谢大家!

这基本上是通过explode完成的:

您可以使用列表将它们直接分配到变量中:

list($date, $ts, $name) = explode('+', '2012-02-19-00-00-00+136571235812571+UserABC.log');

另请参见:

这基本上是通过explode完成的:

您可以使用列表将它们直接分配到变量中:

list($date, $ts, $name) = explode('+', '2012-02-19-00-00-00+136571235812571+UserABC.log');
另请参见:

使用:

输出:

Array
(
    [0] => 2012-02-19-00-00-00
    [1] => 136571235812571
    [2] => UserABC.log
)
使用:

使用:

输出:

Array
(
    [0] => 2012-02-19-00-00-00
    [1] => 136571235812571
    [2] => UserABC.log
)
使用:


如果你想进入微优化领域,不使用正则表达式就可以更快地完成。显然,这取决于编写代码的上下文

$string = "2012-02-19-00-00-00+136571235812571+UserABC.log";
$firstPlusPos = strpos($string, "+");
$secondPlusPos = strpos($string, "+", $firstPlusPos + 1);
$part1 = substr($string, 0, $firstPlusPos);
$part2 = substr($string, $firstPlusPos + 1, $secondPlusPos - $firstPlusPos - 1);
$part3 = substr($string, $secondPlusPos + 1);

这段代码需要0.003,相比之下,我的计算机上的RegEx需要0.007,但这当然会因硬件而异。

如果你想进行微优化,不使用RegEx也可以更快地完成。显然,这取决于编写代码的上下文

$string = "2012-02-19-00-00-00+136571235812571+UserABC.log";
$firstPlusPos = strpos($string, "+");
$secondPlusPos = strpos($string, "+", $firstPlusPos + 1);
$part1 = substr($string, 0, $firstPlusPos);
$part2 = substr($string, $firstPlusPos + 1, $secondPlusPos - $firstPlusPos - 1);
$part3 = substr($string, $secondPlusPos + 1);

这段代码需要0.003,而我的计算机上的正则表达式需要0.007,但这当然会因硬件而异。

不错的解决方案,但我更愿意使用简短干净的代码分解,+1想:不错的解决方案,但我更愿意使用简短干净的代码分解,+1想: