I have a string and this string should be an array.
But the first 2 letters are variable and I need the 5 next digits (whether empty or not). The last 5 digits are numeric with a decimal point or empty ( $string="AB3 . ";)
An example:
$string = "AB10.00";
$arr[0] = "AB";
$arr[1] = "10.00";
I would like to use preg_split() for this.
You mean substr() ?
$string = "AB10.00";
$arr[0] = substr($string, 0, 2); // $arr[0] == 'AB'
$arr[1] = substr($string, 2); // $arr[1] == '10.00'
Related
PHP 7.3.4
When I use
$val = '1,234.00';
echo number_format($val, 2, '.', '');
I get
1 (desired output is 1234.00)
If I do
$val = '1,234.00';
$val = str_replace([',', '$'], '', $val);
echo number_format($val, 2, '.', '');
I get
1234.00
Why doesn't the first one work? What am I missing about the number_format function?
There are 2 important points which need to understand about number_format()
number_format() takes a float as the 1st argument. If string given than convert it in Integer/Float. If found any character in string take the integer part before that character.
return a number with grouped thousands that means a string.
First check the datatype
$a = 1234; // integer
$a = 1234.00; // float
$a = "1234.00"; // string and we can use it as int/float
$a = "1,234.00"; // string but we can't use as int/float because of comma
In first example
$val = '1,234.00';
echo number_format($val, 2, '.', '');
The type of $val is string. So number_format() takes only the int/float part of string and when found any character trim that number. So taking only 1 and you are getting 1.00.
Let's try with
$val = '12,34.00';
echo number_format($val, 2, '.', '');
$val = '12Z34.00'; // also check with this
echo number_format($val, 2, '.', '');
And you will get the result 12.00 for both.You can also check with
$val = 12,34;
echo number_format($val, 2, '.', '');
And you will get
PHP Parse error: syntax error, unexpected ','
That means it not assuming $val as a string. Lets we check with a string without ',' and we will again use number_format() with converted number.
$val = "1234.00";
echo $first = number_format($val, 2, '.', ',');
echo $second = number_format($first, 2, '.', ',');
the output of above example is:
1,234.00
1.00
So $val work like a float number and in $first we are getting a string number and for $second it is separate again with comma and the output is 1.00. So if you have a string with comma, first you need to remove comma from that string then format that using number_format()
I have a question variable e.g. "4X9"
how can i split this into 3 different variables, to have an integer 4, integer 9 and string X ?
I tried using
$arr = explode('X', $question);
$before = $arr[0];
$bbefore = str_replace('"', "", $before);
$newBefore =(int)$before;`
and the same for after.
list($before, $x, $after) = str_split(str_replace('"', '', $question));
1) Explode string by character using str_split()
2) Use list() to make assigning them variables clearer
3) If $before and/or $after are integers you can cast them after this line of code
list($before, $x, $after) = str_split(str_replace('"', '', $question));
$before = (int) $before;
$after = (int) $after;
Demo
I have a string I get from a website.
A portion of the string is "X2" I want to add +1 to 2.
The entire string I get is:
20120815_00_X2
What I want is to add the "X2" +1 until "20120815_00_X13"
You can do :
$string = '20120815_00_X2';
$concat = substr($string, 0, -1);
$num = (integer) substr($string, -1);
$incremented = $concat . ($num + 1);
echo $incremented;
For more informations about substr() see => documentation
You want to find the number at the end of your string and capture it, test for a maximum value of 12 and add one if that's the case, so your pattern would look something like:
/(\d+)$/ // get all digits at the end
and the whole expression:
$new = preg_replace('/(\d+)$/e', "($1 < 13) ? ($1 + 1) : $1", $original);
I have used the e modifier so that the replacement expression will be evaluated as php code.
See the working example at CodePad.
This solution works (no matter what the number after X is):
function myCustomAdd($string)
{
$original = $string;
$new = explode('_',$original);
$a = end($new);
$b = preg_replace("/[^0-9,.]/", "", $a);
$c = $b + 1;
$letters = preg_replace("/[^a-zA-Z,.]/", '', $a);
$d = $new[0].'_'.$new[1].'_'.$letters.$c;
return $d;
}
var_dump(myCustomAdd("20120815_00_X13"));
Output:
string(15) "20120815_00_X14"
I suspect that this has been asked before, but I have no idea what it's actually called, so I couldn't find anything.
I am creating a browser based game in which the player has a 10x10 grid. Each grid square has a few aspects to it, some as binary flags and other as hex values.
To store this information in an array, I want a given cell to contain the following:
"9A0101" where 9A is the tile type, and the 0s and 1s are binary flags about that map tile.
I want to be able to take "9A0101" and split it into "9A", "0", "1", "0", and "1" as separate variables.
TLDR:
How do I slice up a string in PHP? The string will always be the same length, and the parts where I want to cut it will always be at the same offsets.
use substr() to get the parts of string
<?php
echo substr('9A0101', 0,2); // 9A
echo substr('9A0101', 2, 1); // 0
echo substr('9A0101', 3, 1); // 1
echo substr('9A0101', 4, 1); // 0
echo substr('9A0101', 5, 1); // 1
?>
what about substr() ? :
<?php
$str = '9A0101';
echo substr($str,0,2);
echo substr($str,2,1);
echo substr($str,3,1);
echo substr($str,4,1);
echo substr($str,5,1);
?>
You can the substr() function
<?php
$str = "9A0101";
$arr = Array();
$arr[0] = substr($str, -6, 2);
$arr[1] = substr($str, -4, 1);
$arr[2] = substr($str, -3, 1);
$arr[3] = substr($str, -2, 1);
$arr[4] = substr($str, -1, 1);
foreach($arr as $key => $val) {
echo($key . "=>" . $val . '<br/>');
}
?>
Or maybe can use the str_split() function.
$str = "9A0101";
//splitting the string
$array = str_split($str, 2);
var_dump($array);
If you are looking for a single function call, regex can serve you well.
preg_split('~(^..|.)\K~', $string);
The above will split the string on the zero-width position after the first two characters of the string or each subsequent character. \K means forget what is already matched.
If you want to save the 5 values as individual variables, then you can use list() or array destructuring syntax. Demo
[$type, $one, $two, $three, $four] = preg_split('~(^..|.)\K~', $string);
If you wish, you can even access the single byte characters by their string offset. Demo
$type = $string[0] . $string[1];
$one = $string[2];
$two = $string[3];
$three = $string[4];
$four = $string[5];
I want to extract two substrings from a predictably formatted string.
Each string is comprised of letters followed by numbers.
Inputs & Outputs:
MAU120 => MAU and 120
MAUL345 => MAUL and 345
MAUW23 => MAUW and 23
$matches = array();
if ( preg_match('/^([A-Z]+)([0-9]+)$/i', 'MAUL345', $matches) ) {
echo $matches[1]; // MAUL
echo $matches[2]; // 345
}
If you require the MAU you can do:
/^(MAU[A-Z]*)([0-9]+)$/i
Removing i modifier at the end will make the regex case-sensitive.
Try this regular expression:
/(\D*)(\d*)/
PHP code:
$matches = array();
var_dump( preg_match('/(\D*)(\d*)/', 'MAUL345', $matches) );
var_dump( $matches );
Taken literally from your examples:
<?php
$tests = array('MAU120', 'MAUL345', 'MAUW23', 'bob2', '?##!123', 'In the MAUX123 middle.');
header('Content-type: text/plain');
foreach($tests as $test)
{
preg_match('/(MAU[A-Z]?)(\d+)/', $test, $matches);
$str = isset($matches[1]) ? $matches[1] : '';
$num = isset($matches[2]) ? $matches[2] : '';
printf("\$str = %s\n\$num = %d\n\n", $str, $num);
}
?>
Produces:
$test = MAU120
$str = MAU
$num = 120
$test = MAUL345
$str = MAUL
$num = 345
$test = MAUW23
$str = MAUW
$num = 23
$test = bob2
$str =
$num = 0
$test = ?##!123
$str =
$num = 0
$test = In the MAUX123 middle.
$str = MAUX
$num = 123
When you can guarantee that there will be one or more non-numbers and then one or more numbers, you can call upon sscanf() to parse the string.
The native function has multiple advantages over preg_match().
It doesn't return the fullstring match.
It will allow you to type cast substrings depending on the format placeholder you use.
It can return its array or create reference variables -- depending on the number of parameters you feed it.
Code: (Demo)
$tests = [
'MAU120',
'MAUL345',
'MAUW23',
];
foreach ($tests as $test) {
sscanf($test, '%[^0-9]%d', $letters, $numbers);
var_export([$letters, $numbers]);
echo "\n";
}
Output: (notice that the numbers are cast as integer type)
array (
0 => 'MAU',
1 => 120,
)
array (
0 => 'MAUL',
1 => 345,
)
array (
0 => 'MAUW',
1 => 23,
)
If your numbers might start with zero(s) and you want to retain them, you can use %s instead of %d to capture the non-whitespaces substring. If you use %s, then the digits will be cast as a string instead of int-type.
Alternative syntax: (Demo)
foreach ($tests as $test) {
var_export(sscanf($test, '%[^0-9]%d'));
echo "\n";
}