Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find the position of the first occurrence of any number in string

Can someone help me with algorithm for finding the position of the first occurrence of any number in a string?

The code I found on the web does not work:

function my_offset($text){
    preg_match('/^[^\-]*-\D*/', $text, $m);
    return strlen($m[0]);
}
echo my_offset('[HorribleSubs] Bleach - 311 [720p].mkv');
like image 460
Gasper Avatar asked Sep 21 '11 06:09

Gasper


People also ask

How do you find the first occurrence of a number in a string?

To find the index of first occurrence of a substring in a string you can use String. indexOf() function. A string, say str2 , can occur in another string, say str1 , n number of times.

How do you find the position of the first occurrence of a substring in a string in PHP?

The strpos() function finds the position of the first occurrence of a string inside another string. Note: The strpos() function is case-sensitive.

How can you get a first digit of a string in Python?

Each character in this string has a sequence number, and it starts with 0 i.e. In python String provides an [] operator to access any character in the string by index position. We need to pass the index position in the square brackets, and it will return the character at that index.

How do you find the first occurrence of a word in Python?

Use the find() Function to Find First Occurrence in Python We can use the find() function in Python to find the first occurrence of a substring inside a string. The find() function takes the substring as an input parameter and returns the first starting index of the substring inside the main string.


2 Answers

The built-in PHP function strcspn() will do the same as the function in Stanislav Shabalin's answer when used like so:

strcspn( $str , '0123456789' )

Examples:

echo strcspn( 'That will be $2.95 with a coupon.' , '0123456789' ); // 14
echo strcspn( '12 people said yes'                , '0123456789' ); // 0
echo strcspn( 'You are number one!'               , '0123456789' ); // 19

HTH

like image 75
zavaboy Avatar answered Sep 20 '22 08:09

zavaboy


function my_offset($text) {
    preg_match('/\d/', $text, $m, PREG_OFFSET_CAPTURE);
    if (sizeof($m))
        return $m[0][1]; // 24 in your example

    // return anything you need for the case when there's no numbers in the string
    return strlen($text);
}
like image 29
Stanislav Shabalin Avatar answered Sep 20 '22 08:09

Stanislav Shabalin