2

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?

mickmackusa
  • 43,625
  • 12
  • 83
  • 136
MeltingDog
  • 14,310
  • 43
  • 165
  • 295

4 Answers4

4

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.

Obsidian Age
  • 41,205
  • 10
  • 48
  • 71
3

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

Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360
  • Different from other answers, this snippet does not isolate the trimmed trailing digit. (The question is ambiguous about whether both pieces of the input string need to be accessible.) – mickmackusa May 12 '23 at 21:49
0

Use preg_splt :

$str = 'has1numbers2init3';

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

See DEMO

Song
  • 301
  • 1
  • 2
0

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)
);
mickmackusa
  • 43,625
  • 12
  • 83
  • 136