Owen
Owen

Reputation: 7587

Get substring from specific position to last occurring number in string

$str = "234 567 some text following";

How do I get a substring from the third char in the string to the last number?

$positionOfNewLeadingCharacter = 3;

In the above example, I want the substring 4 567 to be returned, not from the third char to the end of the string. 7 is the last occurring digit in the sample string.

The strings in my real application might be a mix of text and numbers. I need to extract the substring FROM a known position TO the position of the last occurring number.

Upvotes: 0

Views: 3443

Answers (6)

mickmackusa
mickmackusa

Reputation: 47991

You want to:

  1. remove characters from the front of the string by nominating the offset of character which which should become the new first character then
  2. remove zero or more non-digital characters from the end of the string.

This can certainly be done with a single preg_match() call, but the human-readability of the pattern isn't great.

Using substr() is a good way to remove the unwanted leading characters -- just make sure that the starting offset is never less than zero or you will get an unintended result. I have not built multibyte support into my snippet.

To start at the 3rd character, you must subtract 1 to start from the 2nd offset.

As for the trimming zero or more (*) non-digital characters (\D) from the end of the string, use the end of string anchor ($).

Code: (Demo)

$str = "234 567 some text following";

$start = 3;

var_export(
    preg_replace(
        '/\D*$/',
        '',
        substr($str, max($start, 1) - 1)
    )
);

Output:

'4 567'

The uglier preg_match() way: (Demo)

var_export(
    preg_match(
        '/.{' . max($start - 1, 0) . '}\K.*\d/',
        $str,
        $match
    )
    ? $match[0]
    : 'no match'
);

Upvotes: 1

Jorgens Lee
Jorgens Lee

Reputation: 1

I just stumbled onto this and thought I'd share my solution.

<?php
$string = "234 567 some text following";
$start = 2;
if(preg_match_all('/\d+/', $string, $sub)){
    $lastNumber = end($sub[0]);
    $newString = substr($string,$start, strrpos($string, $lastNumber) + strlen($lastNumber) - $start);
}
echo $newString;

This line fetches all the numbers in the string

if(preg_match_all('/\d+/', $string, $sub))

And here we fetch the last number

$lastNumber = end($sub[0]); 

Then we find the last occurrence of the number, using strrpos in case the last number occurred more than once. Then, use that position to extract the substring from the starting position to the last number:

$newString = substr($string,$start, strrpos($string, $lastNumber) 
             + strlen($lastNumber) - $start);

Upvotes: 0

jbduzan
jbduzan

Reputation: 1126

you should use substr function

substr($str, 2);

EDIT :

with regex

$pattern = '/^[0-9]+/';
preg_match($pattern, substr($str, 2), $matches, PREG_OFFSET_CAPTURE, 3);
print_r($matches);

EDIT2 : tested and it work

$pattern = '/^([0-9][ ]*)+/';
preg_match($pattern, substr($str, 2), $matches);
print_r($matches);

EDIT3 : didn't see your last edit, building a new one^^

EDIT4 :

$str = "234 567 some text 123 22 following 12 something";
$pattern = '/^([ ]*([0-9][ ]*)*([a-zA-Z][ ]*)*[0-9]*)*[0-9]/';
preg_match($pattern, substr($str, 2), $matches);
echo $matches[0];

give me 4 567 some text 123 22 following 12

is it what you'r expecting ?

EDIT 5 :

new one again ^^

'/^([0-9 :._\-]*[a-zA-Z]*[:._\-]*)*[0-9]/'

Upvotes: 0

Darshit Gajjar
Darshit Gajjar

Reputation: 711

try this:

substr($str,2,strlen($str));

EDIT (NEW ANSWER):

This code is working:

$str = preg_replace( "/\D/", "", $str);
echo substr($str,2);

Upvotes: 0

h2ooooooo
h2ooooooo

Reputation: 39540

You can do this by using a negative lookahead in regex.

<?php
    $lastNumber = getLastNumber("234 567 some text following");
    var_dump($lastNumber);

    function getLastNumber($string) {
        preg_match("/[0-9](?!.*[0-9])/", $string, $match);
        if (!empty($match[0])) return $match[0];
        return false;
    }
?>

Edit: Sorry, I misread; thought you wanted the last standalone number.

Double edit: This seems to do what you want

<?php
    $string = substr("234 567 some text 123 22 following", 2);
    preg_match("/[0-9 ]+/", $string, $matches);
    if (!empty($matches)) {
        $number = intval(str_replace(" ", "", $matches[0]));
        var_dump($number);
    }
?>

As it returns "4567". And of course, it you want the space to stay, simply use $matches[0] instead of $number.

Upvotes: 0

LeonardChallis
LeonardChallis

Reputation: 7783

<?php
  $subStr = substr($str, 2);
?>

By default the length (third parameter), when left out, will default to the end of the string. Note that the characters start at 0, so the third character will be at position 2.

Upvotes: 0

Related Questions