-1

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.

Mat
  • 202,337
  • 40
  • 393
  • 406
Roy
  • 73
  • 1
  • 1
  • 4

4 Answers4

1

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']
Ja͢ck
  • 170,779
  • 38
  • 263
  • 309
0
preg_match("/([a-zA-Z]*)([0-9]*)([a-zA-Z]*)/", $string, $output_array);
print_r($output_array)
gurel_kaynak
  • 546
  • 6
  • 11
0

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
)
Rizier123
  • 58,877
  • 16
  • 101
  • 156
0

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 )
Qarib Haider
  • 4,796
  • 5
  • 27
  • 38