Re: convert string to number
| From: | Burhan Khalid | Date: | Fri, 16 May 2003 16:43:48 +0000 |
| Subject: | Re: convert string to number | ||
| References: | 1 | Groups: | php.general |
| Request: | Send a blank email to php-general+get-147924@lists.php.net to get a copy of this message | ||
Hello Diana,
Friday, May 16, 2003, 10:24:04 AM, you wrote:
DC> is there a function to only find the numeric part of a string, e.g.
DC> it would convert "4 stars" to 4
DC> and what about "four stars" to 4?
A few ways to approach this (some have already been suggested),
however, an easier way might be to use two arrays with the
preg_replace function (
http://www.php.net/manual/en/function.preg-replace.php
)
If your string is always in this format : "[search][space][word]"
which means [search] is what you want out of the string.
So "four stars" "5 stars" "seven baloons" etc would all match.
The first step would be to get the first part of the string.
Easily done using explode :
$strpuzzle = "4 stars";
$parts = explode(" ",$strpuzzle);
$number = $parts[0];
Next step is to create our search and replace arrays :
$search = array("four","five","six", etc.);
$replace = array("4","5","6", etc.);
Finally, we must do our replacing :
$temp = preg_replace($search,$replace,$number);
$number = intval($temp);
--
Best regards,
Burhan