Solved

PHP/REGEX: Find First Number

Posted on 2012-03-22
3
431 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

6 Surprising Benefits of Threat Intelligence

All sorts of threat intelligence is available on the web. Intelligence you can learn from, and use to anticipate and prepare for future attacks.

Join & Write a Comment

Generating table dynamically is the most common issue faced by php developers.... So it seems there is a need of an article that explains the basic concept of generating tables dynamically. It just requires a basic knowledge of html and little maths…
Nothing in an HTTP request can be trusted, including HTTP headers and form data.  A form token is a tool that can be used to guard against request forgeries (CSRF).  This article shows an improved approach to form tokens, making it more difficult to…
The viewer will learn how to dynamically set the form action using jQuery.
The viewer will learn how to look for a specific file type in a local or remote server directory using PHP.

746 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

Need Help in Real-Time?

Connect with top rated Experts

9 Experts available now in Live!

Get 1:1 Help Now