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

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

The code I found on the Internet does not work:

function my_offset($text){ preg_match('/^[^\-]*-\D*/', $text, $m); return strlen($m[0]); } echo my_offset('[HorribleSubs] Bleach - 311 [720p].mkv'); 
+8
source share
5 answers
 function my_ofset($text){ preg_match('/^\D*(?=\d)/', $text, $m); return isset($m[0]) ? strlen($m[0]) : false; } 

should work for this. The original code required that - before the first number, perhaps this was a problem?

+15
source
 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 no numbers in the string return strlen($text); } 
+19
source

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

 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 

NTN

+10
source

I can do regular expressions, but I need to go into an altered state, remember what it does after I encoded it.

Here is a simple PHP function that you can use ...

 function findFirstNum($myString) { $slength = strlen($myString); for ($index = 0; $index < $slength; $index++) { $char = substr($myString, $index, 1); if (is_numeric($char)) { return $index; } } return 0; //no numbers found } 
0
source

Problem

Find the first occurring number in a string

Decision

Here is a regex-free solution in JavaScript

 var findFirstNum = function(str) { let i = 0; let result = ""; let value; while (i<str.length) { if(!isNaN(parseInt(str[i]))) { if (str[i-1] === "-") { result = "-"; } while (!isNaN(parseInt(str[i])) && i<str.length) { result = result + str[i]; i++; } break; } i++; } return parseInt(result); }; 

Input example

 findFirstNum("words and -987 555"); 

Exit

 -987 
0
source

All Articles