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
Related
I have a string something like this:
$string = "small (150 - 160)"
Is there a way I could store 150 in the variable $min and 160 in the variable $max in php?
function minMax($string) {
$digits = explode("-", $string);
return filter_var_array($digits, FILTER_SANITIZE_NUMBER_INT);
}
// $yourString = "small (150 - 160)"
$values = minMax( $yourString );
$min = $values[0]; $max = $values[1];
The function uses explode to remove "-" and create an array. The string to left of "-" is placed in $digits[0] and to right in $digits[1].
PHP filters are then used to remove non integer characters from the array strings. Note I assume you are working with whole numbers. filter_var_array won't work with decimal points but you can use filter_var instead with the FILTER_SANITIZE_NUMBER_FLOAT flag to retain decimals points.
function minMax($string) {
return filter_var($string, FILTER_SANITIZE_NUMBER_FLOAT, FILTER_FLAG_ALLOW_FRACTION );
}
$values = minMax( "small (150 - 160.4)" );
$number = explode("-", $values);
$min = $number[0]; $max = $number[1];
In the decimal example immediately above any "." will be retained. If strings can contain non numeric periods then you will need to remove leadin "."s from your output e.g. if string = "big... (150 - 160.4)" then $min will contain '...150' to prevent leading periods $min = trim($min,'.');.
This PHP script will solve your problem:
$string = "small (150 - 160)";
$tmp = preg_replace("/[^0-9\.]/", " ", $string);
$tmp = trim(preg_replace('/\s+/u', ' ', $tmp));
$tmp = explode(' ', $tmp);
$min = $tmp[0];
$max = $tmp[1];
<?php
$string = "small (150 - 160)";
$string = preg_replace('/[^\d-]/', '', $string); // replace everything not a digit and not a "-" with empty string ('')
list( $min, $max ) = explode('-', $string); // split by "-" and store in $min and $max
var_dump( $min);
var_dump( $max );
Output
string(3) "150"
string(3) "160"
preg_match_all('!\d+!', $string, $matches);
var_dump($matches);
I have a string like this:
9.018E-14
Now I want to convert to this to the normal decimal numbers.
MyGeekPal has a nice article on it.
Code:
<?php
$total_time = 2.8848648071289E-5;
echo exp2dec($total_time);
function exp2dec($number) {
preg_match('/(.*)E-(.*)/', str_replace(".", "", $number), $matches);
$num = "0.";
while ($matches[2] > 0) {
$num .= "0";
$matches[2]--;
}
return $num . $matches[1];
}
?>
If your input is a float
If you have $number = 0.00023459 then printing this value in PHP will probably result in this exponential format. It doesn't mean the variable is stored that way; it's just an output artefact.
Use printf to work around this and gain control over your numeric output.
If your input is a string
Why the complexity?
$matches = Array();
if (preg_match('/(.*)E-(.*)/', $number, $matches)) {
$number = $matches[1] * pow(10, -1*$matches[2]);
}
Though you can tighten up the regex a bit:
$matches = Array();
if (preg_match('/(\d+(?:\.\d+)?)E(-?\d+)/i', $number, $matches)) {
$number = (float)$matches[1] * pow(10, (int)$matches[2]);
}
Live demo
EDIT: Here is some PHP magic:
$stringval = "12e-3";
$numericval = 0 + $stringval;
From the PHP docs:
If the string does not contain any of the characters '.', 'e', or 'E' and the numeric value fits into integer type limits (as defined by PHP_INT_MAX), the string will be evaluated as an integer. In all other cases it will be evaluated as a float.
If you need a more flexible format (e.g. extract four numbers from the same string), use sscanf like this:
$stringval = "12e-3";
$numericval = sscanf($stringval, "%f")[0];
echo $numericval;
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'
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];