Jason
Jason

Reputation: 1137

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!

Upvotes: 1

Views: 82

Answers (3)

gamesmad
gamesmad

Reputation: 409

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.

Upvotes: 1

HamZa
HamZa

Reputation: 14921

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

Upvotes: 1

Ja͢ck
Ja͢ck

Reputation: 173562

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()

Upvotes: 3

Related Questions