Solved

PHP/REGEX: Find First Number

Posted on 2012-03-22
3
444 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 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

Salesforce Made Easy to Use

On-screen guidance at the moment of need enables you & your employees to focus on the core, you can now boost your adoption rates swiftly and simply with one easy tool.

Question has a verified solution.

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

Developers of all skill levels should learn to use current best practices when developing websites. However many developers, new and old, fall into the trap of using deprecated features because this is what so many tutorials and books tell them to u…
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.

739 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