How to extract number from string and assign it into a variable - php

I have a String,
`$str = 'Phone Number 02123456 an Bambang Pamungkas RpTag:749570 RpAdm:2500 Total Rp 750.250';`
i want to extract each number into a variable.
e.g
$Phone_num = ‘02123456';
$RpTag = ‘749570’;
$RpAdm = ‘2500’;
$Total = ‘750250’;
I want the result like as shown above, how do i do that?
P.S sorry for my bad english

You could use preg_match_all here:
$str = 'Phone Number 02123456 an Bambang Pamungkas RpTag:749570 RpAdm:2500 Total Rp 750.250';
preg_match_all("/\b\d+(?:\.\d+)?\b/", $str, $nums);
print_r($nums[0]); // [02123456, 749570, 2500 750.250]
Note that I don't see any point or advantage to having each number in a separate variable. If you really need that, then just iterate the $nums array output from above and make the separate assignments.

Related

How to take input?

I have started to practice coding problems (hackerearth.com) in PHP to increase my problem-solving skill.
As I saw, most of the coding problems are asked for taking input and then output the correct answer based on entered input.
Eg : Input-
The first line consists of two integers N and
K, N being the number of elements in the array and K denotes the
number of steps of rotation.
The next line consists of N space
separated integers , denoting the elements of the array A.
Till now, I know -
fscanf(STDIN, "%d %d\n", $n, $k); //takes N and K
But I don't know how to take an array of size N.
Please help me how to take array of size N. Then It will help me to code further. Else I will just stuck on taking input.
EDIT:
Please help me any PHP pro coder.
EDIT 2:
The problem on which I am still stuck is given below -
Coding challenge -
Monk and Rotation
Monk loves to preform different operations on arrays, and so being the principal of Hackerearth School, he assigned a task to his new student Mishki. Mishki will be provided with an integer array A of size N and an integer K , where she needs to rotate the array in the right direction by K steps and then print the resultant array. As she is new to the school, please help her to complete the task.
EDIT 3 -
Problem can be found here.
What I have tried till know to solve this problem-
fscanf(STDIN, "%s\n", $t);
fscanf(STDIN, "%s %s\n", $n, $k);
//taking 5 numbers seperated by space.
fscanf(STDIN, "%d %d %d %d %d\n", $item1,$item2,$item3,$item4,$item5);
$arr = [$item1,$item2,$item3,$item4,$item5];
for($i = 0; $i<$k; $i++){
array_unshift($arr, array_pop($arr));
}
echo implode(' ', $arr);
You could use readline to read in the space-separated integers, then just split at the spaces to get an array. Note that the array elements will be of type string.
// input string
$string = readline();
// turn into an array
$array = explode(" ", $string);
In hackerearth for PHP you can do something like this -
function getMyInput($n)
{
echo '<pre>';
print_r($n);
}
$t = fgets(STDIN);
for ($t_itr = 0; $t_itr < $t; $t_itr++) {
$n[] = fgets(STDIN);
}
getMyInput($n);
Reference link
PHP standard input?
What does this code mean "ofstream fout(getenv("OUTPUT_PATH"));"
https://www.php.net/manual/en/function.fgets.php
https://www.php.net/manual/en/function.intval.php
Explanation
Use fgets to read a line from the input using STDIN (I/O reading)
then iterate from zero to the maximum provided INPUT and assign those values into a variable.
create a custom method and pass the I/O data (array variable) as an argument to make your own logic for problem-solving.

PHP - get total number of array items with a specific number sequence in value

So, basically I'm trying to count the number of landline phone numbers in a list of both landlines and mobile phone numbers $mobile_list (071234567890,02039989435,0781...)
$mobile_array = explode(",",$mobile_list); // turn into an array
$landlines = array_count_values($mobile_array); // create count variable
echo $landlines["020..."]; // print the number of numbers
So, I get the basic count specific elements function, but I don't see where I can specify if an element 'starts with' or 'contains' a sequence. With the above you can only specify an exact phone number (obviously not useful).
Any help would be great!
I don't see any reason to first explode the string to an array, and then check each array item.
That is a complete waste of performance!
I suggest using preg_match_all and match with word boundary "020".
That means the "word" has to start with 020.
$mobile_list = "071234567890,02039989435,0781,020122,123020";
preg_match_all("/\b020\d+\b/", $mobile_list, $m);
var_dump($m);
echo count($m[0]); // 2
https://3v4l.org/ucSDm
The lightest and fastest method I have found is to explode on ",020".
The array that is returned has item 0 as undefined, meaning we don't know if it's a 020 number so I have to look at that manually.
$temp = explode(",020", $mobile_list);
$cnt = count($temp);
if(substr($temp[0],0,3) != "020") $cnt--;
echo $cnt;
A small scale test shows this as the fastest method.
https://3v4l.org/rD54d
You can use array_reduce() to count the occurrences of strings beginning with '020'
$mobile_list = "02039619491,07143502893,02088024526,07351261813,02095694897";
$mobile_array = explode(',', $mobile_list);
function landlineCount($carry, $item)
{
if (substr($item, 0, 3) === '020') {
return $carry += 1;
}
return $carry;
}
$count = array_reduce($mobile_array, 'landlineCount');
echo $count;
prints 3
I'm sure the OP has finished what they needed to do hours ago but for fun here is a faster way to count the landlines.
I hadn't spotted that the question original code was exploding the string.
That isn't necessary, you can just count the sub strings with substr_count() this could miss the first which wouldn't have a comma before it so I check for that too with substr().
If you need the total count of all numbers you can just count the commas with substr_count() again and add one.
$count = substr($mobile_list, 0, 3) === '020' ? 1 : 0;
$count += substr_count($mobile_list, ",020");
$totalCount = substr_count($mobile_list, ",") + 1;
echo $count;
echo $totalCount;
Here is the bench run a 1000 times to get an average.
https://3v4l.org/Sma66
Use array_filter() or preg_grep() functions to find all numbers that contain or starts with given number sequence.
Note: There is easier and better solution in other answers that cover request to find values that start with given number sequence.
Because you have mentioned - "but I don't see where I can specify if an element 'starts with' or 'contains' a sequence." - My code assumes that you wan't to find any occurrence of sequence, not only in start of string of each item.
$mobile_list = '02000, 02032435, 039002300, 00305600';
$mobile_array = explode(",",$mobile_list); // turn into an array
$landlines = array_count_values($mobile_array); // create count variable
$sequence = '020'; // print the number of numbers
function filter_phone_numbers($mobile_array, $sequence){
return array_filter($mobile_array, function ($item) use ($sequence) {
if (stripos($item, $sequence) !== false) {
return true;
}
return false;
});
}
$filtered_items = array_unique (filter_phone_numbers($mobile_array, $sequence)); //use array_unique in case we find same number that both contains or starts with sequence
echo count($filtered_items);
Or with preg_grep():
$mobile_list = '02000, 02032435, 039002300, 00305600';
$mobile_array = explode(",",$mobile_list); // turn into an array
$landlines = array_count_values($mobile_array); // create count variable
$sequence = preg_quote('020', '~'); ; // print the number of numbers
function grep_phone_numbers($mobile_array, $sequence){
return preg_grep('~' . $sequence . '~', $mobile_array);
}
//use array_unique in case we find same number that both contains or starts with sequence
$filtered_items = array_unique(grep_phone_numbers($mobile_array, $sequence));
echo count($filtered_items);
I recommend doing this with the database. The database is design to manage data and can do it a lot more efficient than PHP can. You can simply put it into a query and just get the result you want in 1 go:
SELECT * FROM phone_numbers WHERE number LIKE '020%'
If you get the data from the database anyways, that LIKE adds a little time to the query, but less that it takes PHP to loop, strpos and store the results. Also, as you return a smaller dataset, less resources are being used.

How to calculate using a POST variable?

I need to multiply this POST variable by 12. As an example, if the amount was 10, the result should say:
Amount: 120
Here's my code so far:
Amount :'.$_POST['my_amount'].'<br/>
I tried to run the calculation in another variable, but this doesn't seem to work:
$result = ($_POST['my_amount'])*12;
or maybe it works and my output code is not working:
$vl_text='';
Amount :'.$_POST['my_amount'].'<br/>'.;
If you want your output to resemble your first example.,.. Amount:120 your missing chunks in each of the following 3 examples. first ensure that your $_POST variable is a valid one and set it to a new variable so you can print out the variable if you need to ...
// if you only expect $_POST['my_amount'] to contain integers...
if(is_int(intval($_POST['my_amount']))){
$my_amount = intval($_POST['my_amount']) * 12;
// or if you expect $_POST['my_amount'] to possibly contain a decimal
if(is_float(floatval($_POST['my_amount']))){
$my_amount = floatval($_POST['my_amount']) * 12;
intval ensures that a variable is cast as an integer if it can be, while not entirely necessary as multiplying in php will do this...its good practice to check any variables that you are using for and math functionality.
floatval does the same for for numbers with decimal. as an integer has to be a whole number if your variable could numbers that could contain decimals... use floatval
all of your examples then need to specify to print/echo the string....so
// your second line
echo 'Amount :'.$my_amount .'<br/>';
// your fourth line...
$vl_text='Amount: '.$my_amount;
echo $vl_text;
}
The most logical explanation is that you get string from POST. A good way to achieve what you want is to convert the POST value to int but keep in mind that it could not be numerical.
$int = (is_numeric($_POST['my_amount']) ? (int)$_POST['my_amount'] : 0); //If POST value is numeric then convert to int. If it's not numeric then convert it to 0
$_POST['my_amount'] = 150;
$data = $_POST['my_amount'] * 12;
echo $data;
Result will be 1800

Php set value as a number

How do I output a value as a number in php? I suspect I have a php value but it is outputting as text and not as a number.
Thanks
Here is the code - Updated for David from question below
<?php
if (preg_match('/\-(\d+)\.asp$/', $pagename1, $a))
{
$pageNumber = $a[1];}
else
{ // failed to match number from URL}
}
?>
If I call it in: This code it does not seem to work.
$maxRows_rs_datareviews = 10;
$pageNum_rs_datareviews = $pagename1; <<<<<------ This is where I want to use it.
if (isset($_GET['pageNum_rs_datareviews'])) {
$pageNum_rs_datareviews = $_GET['pageNum_rs_datareviews'];
}
If I make page name a static number like 3 the code works, if I use $pagename1 it does not, this gives me the idea $pagename1 is not seen as a number?
My stupidity!!!! - I used $pagename1 instead of pageNumber
What kind of number? An integer, decimal, float, something else?
Probably the easiest method is to use printf(), eg
printf('The number %d is an integer', $number);
printf('The number %0.2f has two decimal places', $number);
This might be blindingly obvious but it looks like you want to use
$pageNum_rs_datareviews = $pageNumber;
and not
$pageNum_rs_datareviews = $pagename1;
echo (int)$number; // integer 123
echo (float)$number; // float 123.45
would be the easiest
I prefer to use number_format:
echo number_format(56.30124355436,2).'%'; // 56.30%
echo number_format(56.30124355436,0).'%'; // 56%
$num = 5;
echo $num;
Any output is text, since it's output. It doesn't matter what the type of what you're outputting is, since the human eye will see it as text. It's how you actually treat is in the code is what matters.
Converting (casting) a string to a number is different. You can do stuff like:
$num = (int) $string;
$num = intval($string);
Googling php string to number should give you a beautiful array of choices.
Edit: To scrape a number from something, you can use preg_match('/\d+/', $string, $number). $number will now contain all numbers in $string.

Splitting string on spaces but allow a space in 1 field using regex

This is kind of a follow on from this post: Regex for splitting params out using preg_match
I have this string 1 0 61 12345678 sierra007^7 0 0 123.123.123.123:524 26429 25000 and I need to get each element. It was suggested I use explode which was a great simple solution but now I need to allow spaces in one of the fields.
Someone else posted this regex:
/^([-0-9]+)\s+([-0-9]+)\s+([-0-9]+)\s+([-0-9]+)\s+(\S+)\s+([-0-9])\s+([-0-9]+)\s+([-0-9.:]+)\s+([-0-9.]+)\s+([-0-9.]+)/mx
That does everything else and I was wondering if it could be modified to allow spaces in field 5 (sierra007^7). The only advice I can offer is that the rest of the fields are always numeric (or a colon as you can see) before and after field 5. Is this possible with 1 regex statement or do I need to parse it in PHP and fudge it together?
EDIT: For example, field 5 could be sierra007^7 OR si erra007^7 or si er ra007^7. It would know that it came across field 5 as its the only one that contains a-zA-Z characters. It would know where field 5 ends because field 6 only contains 0-9 characters.
Thanks.
Why not use explode, like the other thread. And count the number of items in the array. If more items are in the array, you put item 5 + any number too high together again with implode..
Eg. your normal row has 10 items. If the resulting explode has 15 items, you:
implode(" ",array_slice($array,5,(count($array)-10)));
If the number of fields never changes, and there's always a value for each field, you can do it using code below:
$fields = explode (' ', $str);
$defaultNumFields = 10;
if (count($fields) > $defaultNumFields) {
for ($i = 5; $i < (count($fields) - $defaultNumFields) + 5; $i++) {
$field[4] .= ' '.$field[$i];
unset($field[$i]);
}
}
$fields = array_values($fields);
That should do it. I might have mis-calcuated and you might need to change the +4 to a +5, test it on a few strings and let me know.

Categories