user1114864
user1114864

Reputation: 1764

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".

Upvotes: 2

Views: 359

Answers (8)

mickmackusa
mickmackusa

Reputation: 47864

Instead of a pattern to capture the digits and match the x, you can simplify the output array by matching the digits and lookahead for the x.

Code: (Demo)

$string = '123x456x78';

preg_match_all('/\d+(?=x)/', $string, $m);
var_export($m[0] ?? null);

Upvotes: 0

cartina
cartina

Reputation: 1419

Use this below code to explode. It works well!

   <?php
    $str='123x456x78';
    $res=explode('x',$str);
    unset($res[count($res)-1]); // remove last array element
    print_r($res);
    ?>

Upvotes: 0

Magnus
Magnus

Reputation: 980

While I'm all for regular expressions, in this case it might be easier to just use PHP's array functions...

$result=array_slice(explode('x',$yourstring),0,-1);

This should work because only the last element returned by explode won't be followed by an 'x'. Not sure if explode will add an empty string as the last element if it ends on 'x' though, you might have to test that...

Upvotes: 0

Anirudh Ramanathan
Anirudh Ramanathan

Reputation: 46728

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" }

Upvotes: 3

d-_-b
d-_-b

Reputation: 23161

To explode AND remove the last result:

$string='123x456x78'; // original string

$res = explode('x', $string); // resulting array, exploded by 'x'

$c = count($res) - 1; // last key #, since array starts at 0 subtract 1

unset($res[$c]); // unset that last value, leaving you with everything else but that.

Upvotes: 0

Class
Class

Reputation: 3160

$var = "123x456x78";
$array = explode("x", $var);
array_pop($array);

Upvotes: 1

silly
silly

Reputation: 7887

use explode

$string='123x456x78';

$res = explode('x', $string);
if(count($res) > 0) {
    echo $res[0];
    if(count($res) > 1) {
        echo $res[1];
    }
}

Upvotes: 1

user529758
user529758

Reputation:

$arr = explode("x", "123x456x78");

and then

unset($arr[2]);

if you really can't stand that poor 78.

Upvotes: 2

Related Questions