简体   繁体   中英

PHP preg_match_all / Regular Expression Issue

I have a string of text that looks like this:

2012-02-19-00-00-00+136571235812571+UserABC.log

I need to break this into three pieces of data: the string to the left of the first + (2012-02-19-00-00-00), the string between the two + (136571235812571) and the string to the right of the + (UserABC.log).

I have this code at the moment:

preg_match_all('\+(.*?)\+', $text, $match);

The issue I'm having is that the code above returns: +136571235812571+

Is there a way to use the RegEx to give me all three pieces of data (without the + marks) or do I need a different approach?

Thank you!

This is basically done with explode() :

explode('+', '2012-02-19-00-00-00+136571235812571+UserABC.log');
// ['2012-02-19-00-00-00', '136571235812571', 'UserABC.log']

You can use list() to assign them directly into variables:

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

See also: explode() list()

Using preg_split() :

$str = '2012-02-19-00-00-00+136571235812571+UserABC.log';
$matches = preg_split('/\+/', $str);
print_r($matches);

Output:

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

Using preg_match_all() :

$str = '2012-02-19-00-00-00+136571235812571+UserABC.log';
preg_match_all('/[^\+]+/', $str, $matches);
print_r($matches);

This can be done "faster" without using RegEx, if you wanted to get into micro optimization. Obviously this depends on the context you are writing the code for.

$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);

This code takes 0.003, compared to 0.007 for RegEx on my computer, but of course this will vary depending on hardware.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM