Jump to content

How to find first number (0-9) in a string?


python72

Recommended Posts

<?php

$str = "hello5world";

$parts = str_split($str);

$first_num = -1;
$num_loc = 0;
foreach ($parts AS $a_char) {
if (is_numeric($a_char)) {
	$first_num = $num_loc;
	break;
}
$num_loc++;
}

if ($first_num > -1) {
echo "found number in $str at index $num_loc <br />";
} else {
echo "no numbers found in $str";
}

?>

If all you need to do is return the position of the first digit in the string, this works. Zero is the position of the first character, but that's easy enough to change. Don't really know if this would more or less efficient than a pattern match, though.

 

<?php
$string = 'This is a string with a 9 number 8.';
$count = strlen($string);
$i = 0;
while( $i < $count ) {
if( ctype_digit($string[$i]) ) {
	echo "First digit found at position $i.";
	return;
}
$i++;
}
?>

 

Returns:

First digit found at position 24.

If you had read the manual page for preg_match you would know the answer to your question. No it does not, but it does return the matched string, so you can create a function that combines preg_match & strpos. Something like this:

<?php
function digpos($str) {
  $pat = '(\d+)';
  preg_match($pat,$str,$matches);
  return(array($matches[0],strpos($str,$matches[0])));
}
$tests = array('sdfj234skdfl;s','this 1s a test','xxxx');
foreach ($tests as $str) {
   list($matstr,$matpos) = digpos($str);
   if ($matpos !== false) {
      echo "The digits [$matstr] were found at position [$matpos] in the string [$str]<br>\n";
   } else {
      echo "No digits were found in the string [$str]<br>\n";
   }
}
?>

 

Ken

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.