get the first number in string if there is one - php

I am looking for a way to extract the first number out of a string. This examples
43
432Phill 21
432hill 21
43#1 Example
43,123 example
should return
43
432
432
43
43,123
I assume it would be possible to use strpos and iterate needle from a-z, A-Z and #. to get all positions and than use the lowest non-zero one to determine the point where number ends. This seems like an overkill. Is there a better way of doing it ?
EDIT: the position is to use substr later. If there is a better way I am down with it.

With a regex, you can extract numbers from a string.
The following statement should do the trick:
preg_match_all('~\d+~', $string, $match);
$match is the array of the numbers contained in $string.

If the number starts at begining you can do this like this:
$number = floatval($string); //it will return float e.g. 432
If you use comma instead of decimal point e.g. 43,123 you must first replace it with dot:
$string = str_replace(',', '.', '43,123 example');

Related

Breaking apart a string in PHP into three parts

I have a serial number string I need to break apart into 3 parts.
The serial numbers look like this:
FOOB123456AB
BAR789123BC
First part: A-Z letters of variable length
Middle part: 6 digit numerical string
Last part: 2 digit letters
How can I break this apart using PHP so I can work with each individual part?
Regular expression can help here. See preg_match().
Try:
$regex = "/^([a-z]*)([\d]{6})(.*)$/i";
$serial = "FOOB123456AB";
$result = preg_match($regex, $serial, $matches);
// result in $matches[1], $matches[2], $matches[3]
This assumes one serial number per string. If you don't have that, text is easy to break up with explode() or similar, and then iterate over the resulting array.

How to refer to the second occurrence of a string in php?

I've been trying to replace my second occurrence for a certain character
For Example:
Hey, I'm trying something With PHP, Is it Working?
I need to get the position of the second comma, I've tried to use strpos but in vain because it's define that it finds the first occurrence of a string so I got Position: 3, any one knows a solution?
The strpos function accepts an optional third parameter which is an offset from which the search for the target string should begin. In this case, you may pass a call to strpos which finds the first index of comma, incremented by one, to find the second comma.
$input = "Hey, I'm trying something With PHP, Is it Working?";
echo strpos($input, ",", strpos($input, ",") + 1); // prints 34
Just for completeness/fun, we could also use a regex substring based approach here, and match the substring up the second comma:
$input = "Hey, I'm trying something With PHP, Is it Working?";
preg_match("/^[^,]*,[^,]*,/", $input, $matches);
echo strlen($matches[0]) - 1; // also prints 34
I know this has been already answered, but a more generic solution to find the last occurrence is to use strrpos.
strrpos accepts a third parameter that can be negative (contrary to strpos).
If negative, the search is performed right to left skipping the last offset bytes of the haystack and searching for the first occurrence of needle.
$foo = "0123456789a123456789b123456789c";
// Looking for '7' right to left from the 5th byte from the end
var_dump(strrpos($foo, '7', -5));

PHP extract only 4digit numbers from string containing 4digit,5digit,6digit numbers

enter image description herei have tried many php functions like strpos(), preg_match() but none of them works. i have a string
i want to extract only the four digit number which is 1234.
<?php
$texxt="abcd1245 784563 1234 98756 kfg7456178";
$results=array();
preg_match('/[0-9]{4}/', $texxt, $results);
print_r($results);
?>
but the above code return 1245 instead of 1234.if i remove the abcd1245 then the out put is 7845.the actual string is very large it containg more than 200 numbers like above. i want only the exact 4 digit number. is there any way to solve this?
You need to place boundaries on both sides of your pattern.
\b\d{4}\b
An alternative would be to use \s instead of \b for whitespace - because boundaries will match other non-alphanumeric characters. Depends on exactly what you're looking for.
See it here
As you said you have more than 200 numbers then use below code:
<?php
$texxt="abcd1245 784563 1234 3421 98756 kfg7456178";
$results=array();
preg_match_all('/\b\d{4}\b/', $texxt, $results);
print_r($results);
?>
preg_match check for only one occurrence, where as preg_match_all check all occurrences.
For regex explanation please refer doc.

check if 5 digit number is available in a string

$st1='dsdsdsd 97537 sdsdd dsddd';
$st2='fdsf 23e sdsd 434 432443454';
$st3='fdf97537 ds344dsddd';
I want to check whether a 5 digit number is available in a string.
st1-- has 5 digit number
st2--- not
st3-- has 5 digit number
A simple regex will do the job.
preg_match('/\d{5}/', $input)
See also http://www.php.net/preg_match
Try this regular expression with preg_match() or preg_match_all()
preg_match("/\b[^\d]*\d{5}[^\d]*\b/", $str);
Let's assume that each element to be checked if this is five digits number is separated by space in string. Therefore you may use explode function to convert string into array of substrings. next you can use is_numeric function to check if that is digit along with check if that sub string is five length long. Also you may use regular expression for that.
Here RegEx is far more better. As I see the #Matt's answer meets these requirements, my comments will be unnecessary.

php preg_replace frustration

Im reluctant to ask but I cant figure out php preg_replace and ignore certain bits of the sting.
$string = '2012042410000102';
$string needs to look like _0424_102
The showing numbers are variable always changing and 2012 changes ever year
what I've tried:
^\d{4}[^\d{4}]10000[^\d{3}]$
^\d{4}[^\d]{4}10000[^\d]{3}$
Any help would be appreciated. I know it's a noob question but easy points for whoever helps.
Thanks
Your first regex is looking for:
The start of the string
Four digits (the year)
Any single character that is not a digit nor { or }
The number 10000
Any single character that is not a digit nor { or }
The end of the string
Your second regex is looking for:
The start of the string
Four digits (the year)
Any four characters that are not digits
The number 10000
Any three characters that are not digits
The end of the string
The regex you're looking for is:
^\d{4}(\d{4})10000(\d{3})$
And the replacement should be:
_$1_$2
This regex looks for:
The start of the string
Four digits (the year)
Capture four digits (the month and day)
The number 10000
Capture three digits (the 102 at the end in your example)
The end of the string
Try the following:
^\d{4}|10000(?=\d{3}$)
This will match either the first four digits in a string, or the string '10000' if there are three digits after '10000' before the end of the string.
You would use it like this:
preg_replace('/^\d{4}|10000(?=\d{3}$)/', '_', $string);
http://codepad.org/itTgEGo4
Just use simple string functions:
$string = '2012042410000102';
$new = '_'.str_replace('10000', '_', substr($string, 4));
http://codepad.org/elRSlCIP
If they're always in the same character locations, regular expressions seem unnecessary. You could use substrings to get the parts you want, like
sprintf('_%s_%s', substr($string,4,4), substr($string,13))
or
'_' . substr($string,4,4) . '_' . substr($string,13)

Categories