Solved

PHP/REGEX: Find First Number

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

PRTG Network Monitor: Intuitive Network Monitoring

Network Monitoring is essential to ensure that computer systems and network devices are running. Use PRTG to monitor LANs, servers, websites, applications and devices, bandwidth, virtual environments, remote systems, IoT, and many more. PRTG is easy to set up & use.

Question has a verified solution.

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

Suggested Solutions

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…
This article discusses how to create an extensible mechanism for linked drop downs.
Explain concepts important to validation of email addresses with regular expressions. Applies to most languages/tools that uses regular expressions. Consider email address RFCs: Look at HTML5 form input element (with type=email) regex pattern: T…
The viewer will learn how to dynamically set the form action using jQuery.

777 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