MeltingDog
MeltingDog

Reputation: 15458

Split string by last character and save to array?

I have several strings that look like:

longname1, anotherlongname2, has1numbers2init3

I would like to use str_split to split off the last character of the strings. Eg:

Array ( [0] => longname [1] => 1 )
Array ( [0] => anotherlongname [1] => 2 )
Array ( [0] => has1numbers2init [1] => 3 )

I can get the number alone using substr($string, -1); but need to find an efficient way of retrieving the remainder of the string.

I have tried:

str_split($string,-1);

but of course this doesn't work.

Would anyone know what I could do?

Upvotes: 2

Views: 2573

Answers (4)

mickmackusa
mickmackusa

Reputation: 47982

To safeguard against splitting too late when a string ends with an integer that is larger than 9, allow matching one or more digits before the end of the string. This will work on all of the question's samples and strings with longer trailing numbers.

My pattern will split on the zero-width position between the last non-digit and the last one or more digits. The \K "forgets" the last non-digits so that it is not consumed during the explosion.

Code: (Demo)

$str = 'has1numbers2init33';

var_export(
    preg_split('/\D\K(?=\d+$)/', $str)
);

Output:

array (
  0 => 'has1numbers2init',
  1 => '33',
)

More basically, split the string on the position before the last character un the string. Demo

var_export(
    preg_split('/(?=.$)/', $str)
);

Upvotes: 0

Song
Song

Reputation: 301

Use preg_splt :

$str = 'has1numbers2init3';

return preg_split('/(\d)$/', $str, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);

See DEMO

Upvotes: 0

Tim Biegeleisen
Tim Biegeleisen

Reputation: 521914

I think that preg_match with an appropriate pattern works better here:

preg_match('/(.*?)\d+$/', "has1numbers2init123", $m);
echo $m[1];

has1numbers2init

Note that this solution is robust to there being more than one digit at the end of the word.

Demo

Upvotes: 3

Obsidian Age
Obsidian Age

Reputation: 42334

You can subtract one from the strlen() of your $string inside of str_split():

<?php

$string = 'longname1';
print_r(str_split($string, strlen($string) - 1));

Output:

Array
(
    [0] => longname
    [1] => 1
)

This can be seen working here.

Upvotes: 4

Related Questions