Splitting a string in multiple values based on string or alphabetic letters?

177 Views Asked by At

I hope I can explain what I'm trying to achieve: In PHP I'm receiving content from a remote website and I want to proces this data. I now have +- 300 strings like this:

$string=abcdefg123abcdefg    

I would like to split this string in 3 parts:

  • first part: first alphabetic string (abcdefg)
  • second part: numeric string (123)
  • third part: second alphabetic string (abcdefg)

I tried some with the explode function but I could only split the string in two parts.

4

There are 4 best solutions below

0
On
preg_match("/([a-zA-Z]*)([0-9]*)([a-zA-Z]*)/", $string, $output_array);
print_r($output_array)
0
On

This should work for you:

(First i get the numbers of the string to explode the string! After that i append the numbers to the array)

<?php

    $string = "abcdefg123abcdefg";

    preg_match('!\d+!', $string, $match);   
    $split = explode(implode("",$match), $string);
    $split[2] = $split[1];
    $split[1] = implode("",$match);

    print_r($split);

?>

Output:

Array
(
    [0] => abcdefg
    [1] => 123
    [2] => abcdefg
)
0
On

You could use preg_split() on a series of digits and also capture the delimiter:

$parts = preg_split('/(\d+)/', 'abc123def', 2, PREG_SPLIT_DELIM_CAPTURE);
// $parts := ['abc', '123', 'def']
0
On

Solution:

This will work:

$string = 'abcdefg123abcde';
preg_match_all('/([0-9]+|[a-zA-Z]+)/',$string,$matches);

print_r( $matches[0] );

Output:

Array ( [0] => abcdefg [1] => 123 [2] => abcde )