How to convert a mixed PHP String into the number only - php

I have a string like this:
$string = 'e.g. 25.32';
I want to pull out only the number (25.32)
The text surrounding the number could potentially be any non-number.

You could use something like :
<?php
$str = "e.g. 25";
$val = (int)$str;
?>
But it's not the best solution.
A "stronger" and universal alternative is...
Code : (UPDATED)
<?php
$str = "e.g. 25.32";
preg_match("/([0-9]+[\.,]?)+/",$str,$matches);
$val = $matches[0];
echo $val;
?>
Output :
25.32
As a function : (UPDATED)
<?php
function getInt($str)
{
preg_match("/([0-9]+[\.,]?)+/",$str,$matches);
return $matches[0];
}
?>
Usage :
<?php
$val = getInt("e.g. 25.32");
?>

If the number is simple:
([0-9]+(?:\.[0-9]+)?)
You then want to match this at the end of the string:
$string = 'e.g. 25.32';
$number = preg_replace('~^.*?([0-9]+(?:\.[0-9]+)?)$~', '$1', $string);
This will make $number contain "25.32", convert it to float if you need the float value:
$float = (float) $number;
This code does only work if there actually is a number. If you can't be sure it is, test first:
$string = 'e.g. 25.32';
$number = NULL;
$hasNumber = preg_match('~([0-9]+(?:\.[0-9]+)?)$~', $string, $matches);
if ($hasNumber)
{
list(, $number) = $matches;
}
If the number can be a number as in PHP:
([+-]?INF|[+-]?(([0-9]+|([0-9]*[\.][0-9]+)|([0-9]+[\.][0-9]*))|([0-9]+|(([0-9]*[\.][0-9]+)|([0-9]+[\.][0-9]*)))[eE][+-]?[0-9]+))
So take care what you actually need to match.

You could use regular expressions if you know the format of your string with preg_match

My old function that also works with negative numbers:
function getNumber($str){
return floatval(preg_replace('/^[^\d-]+/','',$str));
}

Related

PHP showing last string value

I want to display only last string value from string. This is my string ShopTop205/12.50R15
I want to just display this type of string
205/12.50R15
I have tried like
<?php
$catName= 'ShopTop205/12.50R15';
echo substr($catName, strrpos($catName, ' ') + 1);
?>
second way
<?php
$string = 'ShopTop205/12.50R15';
$string = explode('', $string);
$last_string = end($string);
echo $last_string;
?>
I have used substr() function also but i could not get result that i want.
how could i do this ?
You may remove the initial non-numeric chars with a regex:
$catName= 'ShopTop205/12.50R15';
$res = preg_replace('~^\D+~', '', $catName);
echo $res; // => 205/12.50R15
See the PHP demo
The pattern is ^\D+ here, and it matches any one or more (+) chars other than digits (\D) at the start of the string (^).
See the regex demo.
$catName= 'ShopTop205/12.50R15';
$result = substr($catName, 7,20);
print $result;//205/12.50R15;
Check this one
$catName= 'ShopTop205/12.50R15';
preg_match('/^\D*(?=\d)/', $catName, $m);
$pos = isset($m[0]) ? strlen($m[0]) : false;
$text = substr($catName,$pos); // this will contain 205/12.50R15
Doing it with substr() given that the length is always the same:
https://ideone.com/A4Avpt
<?php
echo substr('ShopTop205/12.50R15', -12);
?>
Output: 205/12.50R15

Get all numeric before first Alpha in PHP String

I'm trying to get all numeric before space/alpha in PHP string.
Example:
<?php
//string
$firstStr = '12 Car';
$secondStr = '412 8all';
$thirdStr = '100Pen';
//result I need
firstStr = 12
SecondStr = 412
thirdStr = 100
How do I can get all the number of a string just like example above?
I've an idea to get the position of first Alpha, then get all numeric before that position.
I've successfully get the position using
preg_match('~[a-z]~i', $value, $match, PREG_OFFSET_CAPTURE);
But I'm not done yet to get the numeric before the posisition.
How do I can do that, or anybody know how to fix my idea?
Anyhelp will be appreciated.
You don't need to use regex for strings like the examples you've shown, or any functions at all for that matter. You can just cast them to ints.
$number = (int) $firstStr; // etc.
The PHP rules for string conversion to number will handle it for you.
However, because of those rules, there are some other types of strings that this won't work for. For example, '-12 Car' or '412e2 8all'.
If you do use a regex, be sure to anchor it to the beginning of the string with ^ or it will match digits anywhere in the string as the other regex answers here do.
preg_match('/^\d+/', $string, $match);
$number = $match[0] ?? '';
Here's an extremely hackish approach that will work in most situations:
$s = "1001BigHairyCamels";
$n = intval($s);
$my_number = str_replace($n, '', $s);
$input = '100Pen';
if (preg_match('~(\d+)[ a-zA-Z]~', $input, $m)) {
echo $m[1];
}
This function will do the job!
<?php
function getInt($str){
preg_match_all('!\d+!', $str, $matches);
return $matches[0][0];
}
$firstStr = '12 Car';
$secondStr = '412 8all';
$thirdStr = '100Pen';
echo 'firstStr = '.getInt($firstStr).'<br>';
echo 'secondStr = '.getInt($secondStr).'<br>';
echo 'thirdStr = '.getInt($thirdStr);
?>

count the occurrences of all the letters in a string PHP

I want to count the frequency of occurrences of all the letters in a string. Say I have
$str = "cdcdcdcdeeeef";
I can use str_split and array_count_values to achieve this.
array_count_values(str_split($str));
Wondering if there is another way to do this without converting the string to an array? Thanks
You don't have to convert that into an array() you can use substr_count() to achieve the same.
substr_count — Count the number of substring occurrences
<?php
$str = "cdcdcdcdeeeef";
echo substr_count($str, 'c');
?>
PHP Manual
substr_count() returns the number of times the needle substring occurs in the haystack string. Please note that needle is case sensitive.
EDIT:
Sorry for the misconception, you can use count_chars to have a counted value of each character in a string. An example:
<?php
$str = "cdcdcdcdeeeef";
foreach (count_chars($str, 1) as $strr => $value) {
echo chr($strr) . " occurred a number of $value times in the string." . "<br>";
}
?>
PHP Manual: count_chars
count_chars — Return information about characters used in a string
There is a php function that returns information about characters used in a string: count_chars
Well it might not be what you are looking for, because according to http://php.net/manual/en/function.count-chars.php it
Counts the number of occurrences of every byte-value (0..255) in
string and returns it in various ways
Example from same link (http://php.net/manual/en/function.count-chars.php):
<?php
$data = "Two Ts and one F.";
foreach (count_chars($data, 1) as $i => $val) {
echo "There were $val instance(s) of \"" , chr($i) , "\" in the string.\n";
}
?>
class Strings
{
public function count_of_each_letter($string){
$string_chars = array();
$length_ = mb_strlen($string,'UTF-8');
if($length_== 0){return null;}
else{
for ($i=0; $i < $length_; $i++) {
$each_letter = mb_substr($string,0,1,'UTF-8');
$string_chars[$each_letter] = mb_substr_count($string, $each_letter);
$string = str_replace($each_letter,"", $string);
$length_ = mb_strlen($string,'UTF-8');
}
$string = '';
foreach ($string_chars as $key => $value) {
$string .= $key.'-'.$value.'<br>';
}
return $string;
}
}
}
$new_counter = new Strings();
echo $new_counter::count_of_each_letter('ختواجرایآهنگبهصورتتکنفرهنمود.اوازسال۱۹۷۲تا۱۹۷۵،۴آلبوماستودیوییتک‌نفرهمنتشرکردوحتینامزدیکجایزهاسکارهمشد.درهمینسال‌هاگروهاقدامبهبرگزاریتورکنسرتدراروپاونیزیکتورجهانیکردند.جکسونفایودرسال۱۹۷۵ازشرکتنشرموسیقیموتاونرکوردزبهسی‌بی‌اسرکوردزنقلمکانکردند.گروههمچنانبهاجراهایبین‌المللیخودادامهمی‌دادواز۱۹۷۶تا۱۹۸۴(از۱۵تا۲۴سالگیمایکل)ششآلبوماستودیوییدیگرمنتشرکرد.درهمینمدت،مایکلترانه‌سرایاصلیگروهجکسونزبود.Cantional,oderGesangbuchAugsburgischerKonfessionin1627.ohannSebastianBachcomposedafour-partsetting,BWV285,whichiswithouttext.twaspublishedasNo.196inthecollectionofchoralesbyJohannPhilippKirnbergerundCarlPhilippEmanufread');
you can do it by following way as well:
$str = 'aabbbccccdddeeedfff';
$arr = str_split($str);
$result = array_count_values($arr);
$string = http_build_query($result,'','');
echo str_replace('=','',$string);

how to parse str in variable

I am trying to parse following text in variable...
$str = 3,283,518(10,569 / 2,173)
And i am using following code to get 3,283,518
$arr = explode('(',$str);
$num = str_replace(',','',$arr[0]); //prints 3283518
the above $str is dynamic and sometimes it could be only 3,283,518(means w/o ()) so explode function will throw an error so what is the best way to get this value? thanks.
$str = "3,283,518(10,569 / 2,173)";
preg_match("/[0-9,]+/", $str, $res);
$match = str_replace(",", "", array_pop($res));
print $match;
This will return 3283518, simply by taking the first part of the string $str that only consists of numbers and commas. This would also work for just 3,283,518 or 3,283,518*10,569, etc.
Probably going to need more information from you about how dynamic $str really is but if its just between those values you could probably do the following
if (strpos($str, '(' ) !== false) {
$arr = explode('(',$str);
$num = str_replace(',','',$arr[0]);
} else {
//who knows what you want to do here.
}
If you are really sure about number format, you can try something like:
^([0-9]+,)*([0-9]+)
Use it with preg_match for example.
But if it is not a simple format, you should go with an arithmetic expressions parser.
Analog solution:
<?php
$str = '3,283,518(10,569 / 2,173)';
if (strstr($str, '('))
{
$arr = explode('(',$str);
$num = str_replace(',','',$arr[0]);
}
else
{
$num = str_replace(',','',$str);
}
echo $num;
?>

PHP Extract numbers from a string

I want to extract numbers from a string in PHP like following :
if the string = 'make1to6' i would like to extract the numeric character before and after the 'to' substring in the entire string. i.e. 1 and 6 are to be extracted
i will be using these returned values for some calculations.' i would like to extract the numeric character before and after the 'to' substring in the entire string. i.e. 1 and 6 are to be extracted
The length of the string is not fixed and can be a max of 10 characters in length.The number can be of max two digits on either side of 'to' in the string.
Some example string values :
sure1to3
ic3to9ltd
anna1to6
joy1to4val
make6to12
ext12to36
thinking of something like :
function beforeTo(string) {
return numeric_value_before_'to'_in_the_string;
}
function afterTo(string) {
return numeric_value_after_'to'_in_the_string;
}
i will be using these returned values for some calculations.
You could use preg_match_all to achive this:
function getNumbersFromString($str) {
$matches = array();
preg_match_all('/([0-9]+)/', $str, $matches);
return $matches;
}
$matches = getNumbersFromString('hej 12jippi77');
Use preg_match with a regex that will extract the numbers for you. Something like this should do the trick for you:
$matches = null;
$returnValue = preg_match('/([\d+])to([\d+])/uis', 'ic3to9ltd', $matches);
After this $matches will look like:
array (
0 => '3to9',
1 => '3',
2 => '9',
);
You should read somewhat on regular expressions, it's not hard to do stuff like this if you know how they work. Will make your life easier. ;-)
You can use a regular expression as such, it should match exactly your specification:
$string = 'make6to12';
preg_match('{^.*?(?P<before>\d{1,2})to(?P<after>\d{1,2})}m', $string, $match);
echo $match['before'].', '.$match['after']; // 6, 12
You can use this:
// $str holds the string in question
if (preg_match('/(\d+)to(\d+)/', $str, $matches)) {
$number1 = $matches[1];
$number2 = $matches[2];
}
You can use regular expressions.
$string = 'make1to6';
if (preg_match('/(\d{1,10})to(\d{1,10})/', $string, $matches)) {
$number1 = (int) $matches[1];
$number2 = (int) $matches[2];
} else {
// Not found...
}
<?php
$data = <<<EOF
sure1to3
ic3to9ltd
anna1to6
joy1to4val
make6to12
ext12to36
EOF;
preg_match_all('#(\d+)to(\d+)#s', $data, $matches);
header('Content-Type: text/plain');
//print_r($matches);
foreach($matches as $match)
{
echo sprintf("%d, %d\n", $match[1], $match[2]);
}
?>
This is what Regular Expressions are for - you can match multiple instances of very specific patterns and have them returned to you in an array. It's pretty awesome, truth be told :)
Take a look here for how to use the built in regular expression methods in php : LINK
And here is a fantastic tool for testing regular expressions: LINK
<?php
list($before, $after) = explode('to', 'sure1to3');
$before_to = extract_ints($before);
$after_to = extract_ints($after);
function extract_ints($string) {
$ints = array();
$len = strlen($string);
for($i=0; $i < $len; $i++) {
$char = $string{$i};
if(is_numeric($char)) {
$ints[] = intval($char);
}
}
return $ints;
}
?>
A regex seems really unnecessary here since all you are doing is checking is_numeric() against a bunch of characters.

Categories