Search code examples
phparraysstringexplodedelimiter

Extract all numeric substrings which are followed by a particular character


If I have a string "123x456x78", how could I explode it to return an array containing "123" as the first element and "456" as the second element? Basically, I want to take strings that are followed by "x" (which is why "78" should be thrown out). I've been messing around with regular expressions, but am having trouble.

EDIT: if the string were "123x456x78x" I would need three elements: "123", "456", "78". Basically, for each region following an "x", I need to record the string up until the next "x".


Solution

  • Loads of different ways, but here's a RegEx as you were trying that:

    $str = "123x456x78";
    preg_match_all("/(\d+)x/", $str, $matches);
    var_dump($matches[1]);
    

    Output:

    array(2) { [0]=> string(3) "123" [1]=> string(3) "456" }