php string explode on (-) characters - php

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);

Related

Split string into 3 random-length parts

I have a string and I want to split it into 3 random-length parts (without caring about string length is the objective) to get 3 strings.
$mystring = "aHR0cHM6Ly93d3cucGhwLm5ldC9tYW51YWwvZW4vZnVuY3Rpb24uc3RyLXNwbGl0LnBocA==";
When I tried to use str_split(), I always have to manually set the number of character per string.
If I calculate the string length and divide it by 3, sometimes I get non-whole numbers.
$len = strlen($mystring);
$len = $len / 3;
$parts = str_split($mystring, $len);
print_r($parts);
Even if you want random then I assume you still don't want 0 length strings.
I use random values between 1 and string length (minus some, to make sure you don't run out of characters).
$mystring = "aHR0cHM6Ly93d3cucGhwLm5ldC9tYW51YWwvZW4vZnVuY3Rpb24uc3RyLXNwbGl0LnBocA==";
$len=strlen($mystring);
$parts[] = substr($mystring, 0, $l[] = rand(1,$len-5));
$parts[] = substr($mystring, $l[0], $l[] = rand(1,$len-$l[0]-3));
$parts[] = substr($mystring, array_sum($l));
print_r($parts);
The code grabs parts of the string depending on what the previous random value was.
https://3v4l.org/v4nUF
A more generic solution could look like this:
function split_random_parts($string, $part_count) {
$result = [];
for ($i = 0; $i < $part_count - 1; $i++) {
// Always leave part_count - i characters remaining so that no empty string gets created
$len = rand(1, strlen($string) - ($part_count - $i));
$result[] = substr($string, 0, $len);
$string = substr($string, $len);
}
$result[] = $string;
return $result;
}
Something like this would do it:
$mystring = "aHR0cHM6Ly93d3cucGhwLm5ldC9tYW51YWwvZW4vZnVuY3Rpb24uc3RyLXNwbGl0LnBocA==";
$part3 = substr($mystring, rand(2,(strlen($mystring)-2)));
$mystring = substr($mystring, 0, (strlen($mystring)-strlen($part3)));
$part2 = substr($mystring, rand(1,(strlen($mystring)-1)));
$mystring = substr($mystring, 0, (strlen($mystring)-strlen($part2)));
$part1 = $mystring;
var_dump($part1, $part2, $part3);
This code would produce results such as:
string(67) "aHR0cHM6Ly93d3cucGhwLm5ldC9tYW51YWwvZW4vZnVuY3Rpb24uc3RyLXNwbGl0LnB"
string(1) "o"
string(4) "cA=="
string(57) "aHR0cHM6Ly93d3cucGhwLm5ldC9tYW51YWwvZW4vZnVuY3Rpb24uc3RyL"
string(5) "XNwbG"
string(10) "l0LnBocA=="
string(31) "aHR0cHM6Ly93d3cucGhwLm5ldC9tYW5"
string(27) "1YWwvZW4vZnVuY3Rpb24uc3RyLX"
string(14) "NwbGl0LnBocA=="
string(5) "aHR0c"
string(23) "HM6Ly93d3cucGhwLm5ldC9t"
string(44) "YW51YWwvZW4vZnVuY3Rpb24uc3RyLXNwbGl0LnBocA=="
I mean you just need to round up the result of length division like:
<?php
$mystring = "The any size string ...";
$len=strlen($mystring);
$chunk=ceil($len/3);
$parts = str_split($mystring , $chunk);
print_r($parts);
Here the fiddle
If you need divide to 3 without random length, may you use str_pad like
$str = 'aHR0cHM6Ly93d3cnVuY3Rpb24uc3RyLXNwbGl0LnBocA==';
$divide = 3;
$char = '*'; // that not used in your string
$add = $divide - strlen($str) % $divide;
$total = strlen($str) + $add;
$str = str_pad($str, $total, $char, STR_PAD_LEFT);
//string(48) "**aHR0cHM6Ly93d3cnVuY3Rpb24uc3RyLXNwbGl0LnBocA=="
$result = str_split($str, $total / $divide );
/*array(3) {
[0]=> string(16) "**aHR0cHM6Ly93d3"
[1]=> string(16) "cnVuY3Rpb24uc3Ry"
[2]=> string(16) "LXNwbGl0LnBocA=="
}*/
keep in mind that strip '*' chars before decode
$result = str_replace('*', '', $result);
Demo
Because your input string contains no whitespace characters, you can use sscanf() with %s placeholders with explicit substring lengths (for the first two substrings) to explode the string on dynamic points.
Code: (Demo)
$mystring = "aHR0cHM6Ly93d3cucGhwLm5ldC9tYW51YWwvZW4vZnVuY3Rpb24uc3RyLXNwbGl0LnBocA==";
$len = strlen($mystring);
$end_of_first = rand(1, $len - 2);
$end_of_middle = rand(1, $len - $end_of_first - 1);
var_export(sscanf($mystring, "%{$end_of_first}s%{$end_of_middle}s%s"));
For anyone else who might have whitespaces in their input string, you can replace the s with [^~] where the ~ should be a character that is guaranteed to not occur in your string.
For an approach that accommodates a variable number of segments, a decementing loop seems appropriate.
Code: (Demo)
$totalSegments = 4;
$segments = [];
while ($totalSegments) {
--$totalSegments;
$segmentLength = rand(1, strlen($mystring) - $totalSegments);
[$segments[], $mystring] = sscanf($mystring, "%{$segmentLength}s%s");
}
var_export($segments);

Saving values from a variable to an array

I have a long string variable that contains coordinates
I want to keep each coordinate in a separate cell in the array according to Lat and Lon..
For example. The following string:
string = "(33.110029967689556, 35.60865999564635), (33.093492845160036, 35.63955904349791), (33.0916232355565, 35.602995170206896)";
I want this:
arrayX[0] = "33.110029967689556";
arrayX[1] = "33.093492845160036";
arrayX[2] = "33.0916232355565";
arrayY[0] = "35.60865999564635";
arrayY[1] = "35.63955904349791";
arrayY[2] = "35.602995170206896";
Does anyone have an idea ?
Thanks
Use substr to modify sub string, it allow you to do that with a little line of code.
$array_temp = explode('),', $string);
$arrayX = [];
$arrayY = [];
foreach($array_temp as $at)
{
$at = substr($at, 1);
list($arrayX[], $arrayY[]) = explode(',', $at);
}
print_r($arrayX);
print_r($arrayY);
The simplest way is probably to use a regex to match each tuple:
Each number is a combination of digits and .: the regex [\d\.]+ matches that;
Each coordinate has the following format: (, number, ,, space, number,). The regex is \([\d\.]+,\s*[\d\.]+\).
Then you can capture each number by using parenthesis: \(([\d\.]+),\s*([\d\.]+)\). This will produce to capturing groups: the first will contain the X coordinate and the second the Y.
This regex can be used with the method preg_match_all.
<?php
$string = '(33.110029967689556, 35.60865999564635), (33.093492845160036, 35.63955904349791), (33.0916232355565, 35.602995170206896)';
preg_match_all('/\(([\d\.]+)\s*,\s*([\d\.]+)\)/', $string, $matches);
$arrayX = $matches['1'];
$arrayY = $matches['2'];
var_dump($arrayX);
var_dump($arrayY);
For a live example see http://sandbox.onlinephpfunctions.com/code/082e8454486dc568a6557058fef68d6f10c8dbd0
My suggestion, working example here: https://3v4l.org/W99Uu
$string = "(33.110029967689556, 35.60865999564635), (33.093492845160036, 35.63955904349791), (33.0916232355565, 35.602995170206896)";
// Split by each X/Y pair
$array = explode("), ", $string);
// Init result arrays
$arrayX = array();
$arrayY = array();
foreach($array as $pair) {
// Remove parentheses
$pair = str_replace('(', '', $pair);
$pair = str_replace(')', '', $pair);
// Split into two strings
$arrPair = explode(", ", $pair);
// Add the strings to the result arrays
$arrayX[] = $arrPair[0];
$arrayY[] = $arrPair[1];
}
You need first to split the string into an array. Then you clean the value to get only the numbers. Finally, you put the new value into the new array.
<?php
$string = "(33.110029967689556, 35.60865999564635), (33.093492845160036, 35.63955904349791), (33.0916232355565, 35.602995170206896)";
$loca = explode(", ", $string);
$arr_x = array();
$arr_y = array();
$i = 1;
foreach($loca as $index => $value){
$i++;
if ($i % 2 == 0) {
$arr_x[] = preg_replace('/[^0-9.]/', '', $value);
}else{
$arr_y[] = preg_replace('/[^0-9.]/', '', $value);
}
}
print_r($arr_x);
print_r($arr_y);
You can test it here :
http://sandbox.onlinephpfunctions.com/code/4bf04e7aabeba15ecfa114d8951eb771610a43a4

how to trim a string into two Integers and one string (php)?

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

How to convert Exponentials to Decimals in PHP

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;

Add +1 to a string obtained from another site

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"

Categories