?
Solved

PHP/REGEX: Find First Number

Posted on 2012-03-22
3
Medium Priority
?
451 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 2000 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

Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

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

This article discusses how to implement server side field validation and display customized error messages to the client.
Originally, this post was published on Monitis Blog, you can check it here . In business circles, we sometimes hear that today is the “age of the customer.” And so it is. Thanks to the enormous advances over the past few years in consumer techno…
The viewer will learn how to dynamically set the form action using jQuery.
The viewer will learn how to create a basic form using some HTML5 and PHP for later processing. Set up your basic HTML file. Open your form tag and set the method and action attributes.: (CODE) Set up your first few inputs one for the name and …
Suggested Courses

800 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