Solved

PHP/REGEX: Find First Number

Posted on 2012-03-22
3
442 Views
Last Modified: 2012-03-22
Using PHP, how can I find the first number?

<?php

echo firstNumber('abc 123 hello 567'); // Should echo 123
echo firstNumber('5 abc 123 hello 567'); // Should echo 5
echo firstNumber('abc hello'); // Should not echo anything

?>
0
Comment
Question by:hankknight
  • 2
3 Comments
 
LVL 35

Accepted Solution

by:
Terry Woods earned 500 total points
ID: 37755303
Tested and working:

function firstNumber($mytext) {
  if (preg_match("/\d+/",$mytext, $matches))
    return $matches[0];
  else
    return "";
}
0
 
LVL 16

Author Comment

by:hankknight
ID: 37755319
Thanks, TerryAtOpus, but I get an error:
Notice: Undefined offset

<?php

echo firstNumber('abc 123 hello 567'); // Should echo 123
echo firstNumber('5 abc 123 hello 567'); // Should echo 5
echo firstNumber('abc hello'); // Should not echo anything
echo firstNumber('abc4hello'); // Should echo 4

function firstNumber($mytext) {
  if (preg_match("/\d+/",$mytext, $matches))
    return $matches[1];
  else
    return "";
}

?>

Open in new window

0
 
LVL 35

Expert Comment

by:Terry Woods
ID: 37755327
I did an edit to fix a bug in it when I tested it - it should be $matches[0]
0

Featured Post

Free Tool: ZipGrep

ZipGrep is a utility that can list and search zip (.war, .ear, .jar, etc) archives for text patterns, without the need to extract the archive's contents.

One of a set of tools we're offering as a way to say thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Introduction HTML checkboxes provide the perfect way for a web developer to receive client input when the client's options might be none, one or many.  But the PHP code for processing the checkboxes can be confusing at first.  What if a checkbox is…
Author Note: Since this E-E article was originally written, years ago, formal testing has come into common use in the world of PHP.  PHPUnit (http://en.wikipedia.org/wiki/PHPUnit) and similar technologies have enjoyed wide adoption, making it possib…
The viewer will learn how to count occurrences of each item in an array.
The viewer will learn how to look for a specific file type in a local or remote server directory using PHP.

839 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question