Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP Explode between an integer and letter

Tags:

regex

php

explode

array (    
    [0] => 3 / 4 Bananas
    [1] => 1 / 7 Apples
    [2] => 3 / 3 Kiwis
    )

Is it possible, to say, iterate through this list, and explode between the first letter and first integer found, so I could seperate the text from the set of numbers and end up with something like:

array (
   [0] => Bananas
   [1] => Apples
   [2] => Kiwis
   )

I have no idea how you would specify this as the delimiter. Is it even possible?

foreach ($fruit_array as $line) {
   $var = explode("??", $line);
}

Edit: updated example. exploding by a space wouldn't work. see above example.

like image 954
Norse Avatar asked Feb 17 '26 13:02

Norse


1 Answers

You could use preg_match instead of explode:

$fruit_array = array("3 / 4 Bananas", "1 / 7 Apples", "3 / 3 Kiwis");
$result = array();
foreach ($fruit_array as $line) {
   preg_match("/\d[^A-Za-z]+([A-Za-z\s]+)/", $line, $match);
   array_push($result, $match[1]);
}

It will almost literally match your expression, that is, a digit \d, followed by one or more non-letters [^A-Za-z], followed by one or more letters or whitespace (to account for multiple words) [A-Za-z\s]+. This final matched string, between parentheses, will be captured in the first match, i.e., $match[1].

Here's a DEMO.

like image 193
João Silva Avatar answered Feb 19 '26 03:02

João Silva