good_evening
good_evening

Reputation: 21749

Include matched part in regular expression

My try:

$a = preg_split("/[0-9](\-)[0-9]/", $d);
print_r($a);

If $d=sometext9-9sometext, I want to be able to get from print_r($a);

Array
(
    [0] => sometext9
    [1] => -
    [2] => 9sometext
)

What am I missing?

Upvotes: 2

Views: 42

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626893

You may use

$re = "/(?<=[0-9])(-)(?=[0-9])/"; 
$str = "sometext9-9sometext"; 
$a = preg_split($re, $str, $matches, PREG_SPLIT_DELIM_CAPTURE);
print_r($a);

See IDEONE demo. Since the - is in Group 1 (enclosed with (...)) and we use PREG_SPLIT_DELIM_CAPTURE flag, the hyphen is returned as part of the resulting array.

PREG_SPLIT_DELIM_CAPTURE
If this flag is set, parenthesized expression in the delimiter pattern will be captured and returned as well.

The lookarounds (?<=[0-9]) and (?=[0-9]) check for but do not consume the digits on both ends thus they are kept in the elements adjoining to -. See more on that behavior at Lookarounds Stand their Ground.

Upvotes: 3

Related Questions