Reputation: 372
I have the following string, and want to split the name from the invoiceid. The name could have a space, and possibly a hyphen as well.
$invoice_id ="May-Ann Jane-28188-1600086909";
$invoice_id ="May-Ann Jane-28188-1600086909";
$exploded = preg_split('/[-]+[0-9]/', $invoice_id,3 );
foreach($exploded as $index => $answer){
if (!empty($answer)){
echo $index.": ".$answer."<br />";
}
}
$prefix = $exploded[0];
$invoiceid = $exploded[1];
$transid = $exploded[2];
echo '<BR>list2:<BR />';
echo "prefix :".$prefix."<br />";
echo "invoiceid :".$invoiceid."<br />";
On the output, the first character of any number is lost:
0: May-Ann Jane
1: 8188
2: 600086909
list2:
prefix :May-Ann Jane
invoiceid :8188
transid :600086909
how do I get that first character back?
Upvotes: 1
Views: 42
Reputation: 163217
You can split using a positive lookahead (?=
asserting a digit on the right instead of matching it. That way you keep the digit.
-(?=[0-9])
$invoice_id ="May-Ann Jane-28188-1600086909";
$exploded = preg_split('/-(?=[0-9])/', $invoice_id, 3);
print_r($exploded);
Output
Array
(
[0] => May-Ann Jane
[1] => 28188
[2] => 1600086909
)
Upvotes: 1