Take a part of a string (PHP) - php

We are trying to get certain parts of a String.
We have the string:
location:32:DaD+LoC:102AD:Ammount:294
And we would like to put the information in different strings. For example $location=32 and $Dad+Loc=102AD
The values vary per string but it will always have this construction:
location:{number}:DaD+LoC:{code}:Ammount:{number}
So... how do we get those values?

That would produce what you want, but for example $dad+Loc is an invalid variable name in PHP so it wont work the way you want it, better work with an array or an stdClass Object instead of single variables.
$string = "location:32:DaD+LoC:102AD:Ammount:294";
$stringParts = explode(":",$string);
$variableHolder = array();
for($i = 0;$i <= count($stringParts);$i = $i+2){
${$stringParts[$i]} = $stringParts[$i+1];
}
var_dump($location,$DaD+LoC,$Ammount);

Easy fast forward approach:
$string = "location:32:DaD+LoC:102AD:Ammount:294";
$arr = explode(":",$string);
$location= $arr[1];
$DaD_LoC= $arr[3];
$Ammount= $arr[5];

$StringArray = explode ( ":" , $string)

By using preg_split and mapping the resulting array into an associative one.
Like this:
$str = 'location:32:DaD+LoC:102AD:Ammount:294';
$list = preg_split('/:/', $str);
$result = array();
for ($i = 0; $i < sizeof($list); $i = $i+2) {
$result[$array[$i]] = $array[$i+1];
};
print_r($result);

it seems nobody can do it properly
$string = "location:32:DaD+LoC:102AD:Ammount:294";
list(,$location,, $dadloc,,$amount) = explode(':', $string);

the php function split is deprecated so instead of this it is recommended to use preg_split or explode.
very useful in this case is the function list():
list($location, $Dad_Loc, $ammount) = explode(':', $string);
EDIT:
my code has an error:
list(,$location,, $Dad_Loc,, $ammount) = explode(':', $string);

Related

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 truncate a delimited string in PHP?

I have a string of delimited numerical values just like this:
5|2288|502|4208|55|23217|235|10|3845|19053|1885|61|324|9004| ...etc.
Depending on the circumstance, the string may have only 1 value, 15 values, all the way up to 100s of values, all pipe delimited.
I need to count off (and keep/echo) the first 10 values and truncate everything else after that.
I've been looking at all the PHP string functions, but have been unsuccessful in finding a method to handle this directly.
Use explode() to separate the elements into an array, then you can slice off the first 10, and implode() them to create the new string.
$arr = "5|2288|502|4208|55|23217|235|10|3845|19053|1885|61|324|9004";
$a = explode ('|',$arr);
$b = array_slice($a,0,10);
$c = implode('|', $b);
Use PHP Explode function
$arr = explode("|",$str);
It will break complete string into an array.
EG: arr[0] = 5, arr[1] = 2288 .....
I would use explode to separate the string into an array then echo the first ten results like this
$string = "5|2288|502|4208|55|23217|235|10|3845|19053|1885|61|324|9004";
$arr = explode("|", $string);
for($i = 0; $i < 10; $i++){
echo $arr[$i];
}
Please try below code
$str = '5|2288|502|4208|55|23217|235|10|3845|19053|1885|61|324';
$arrayString = explode('|', $str);
$cnt = 0;
$finalVar = '';
foreach ($arrayString as $data) {
if ($cnt > 10) {
break;
}
$finalVar .= $data . '|';
$cnt++;
}
$finalVar = rtrim($finalVar, '|');
echo $finalVar;

How to expand a string with PHP, using the FROM and TO numbers specified within square brackets?

Let’s say I have the string http://www.example.com/images/[1-12].jpg. I would like to expand it into:
http://www.example.com/images/1.jpg
http://www.example.com/images/2.jpg
http://www.example.com/images/3.jpg
http://www.example.com/images/4.jpg
http://www.example.com/images/5.jpg
http://www.example.com/images/6.jpg
http://www.example.com/images/7.jpg
http://www.example.com/images/8.jpg
http://www.example.com/images/9.jpg
http://www.example.com/images/10.jpg
http://www.example.com/images/11.jpg
http://www.example.com/images/12.jpg
Here is my code:
$str = "http://www.example.com/images/[1-12].jpg";
while(preg_match_all("/^([^\\[\\]]*)\\[(\\d+)\\-(\\d+)\\](.*)$/m", $str, $mat)){
$arr = array();
$num = sizeof($mat[0]);
for($i = 0; $i < $num; $i++){
for($j = $mat[2][$i]; $j <= $mat[3][$i]; $j++){
$arr[] = rtrim($mat[1][$i].$j.$mat[4][$i]);
}
}
$str = implode(PHP_EOL, $arr);
}
It works fine even if I change $str to a more complex expression like the following:
$str = "http://www.example.com/images/[1-4]/[5-8]/[9-14].jpg";
But, unfortunately, zero-padded integers are not supported. So, if I begin with:
$str = "http://www.example.com/images/[001-004].jpg";
Expected result:
http://www.example.com/images/001.jpg
http://www.example.com/images/002.jpg
http://www.example.com/images/003.jpg
http://www.example.com/images/004.jpg
And the actual result:
http://www.example.com/images/001.jpg
http://www.example.com/images/2.jpg
http://www.example.com/images/3.jpg
http://www.example.com/images/4.jpg
How to change this behaviour so that my code produces the expected result? Also, what are the other shortcomings of my code? Should I really do it with the while loop and preg_match_all or are there faster alternatives?
UPDATE: Changing the seventh line of my code into
$arr[] = rtrim($mat[1][$i].str_pad($j, strlen($mat[2][$i]), 0, STR_PAD_LEFT).$mat[4][$i]);
seems to do the trick. Thanks a lot to sjagr for suggesting this. My question is still open because I would like to know the shortcomings of my code and faster alternatives (if any).
Per #SoumalyoBardhan's request, my suggestion/answer:
If you use str_pad(), you can force the padding based on the size of the matched string using strlen() found by your match. Your usage of it looks good to me:
$arr[] = rtrim($mat[1][$i].str_pad($j, strlen($mat[2][$i]), 0, STR_PAD_LEFT).$mat[4][$i]);
I really can't see what else could be improved with your code, although I don't exactly understand how preg_match_all would be used in a while statement.
A faster alternative with preg_split which also supports descending order (FROM > TO):
$str = "http://www.example.com/images/[12-01].jpg";
$spl = preg_split("/\\[([0-9]+)-([0-9]+)\\]/", $str, -1, 2);
$size = sizeof($spl);
$arr = array("");
for($i = 0; $i < $size; $i++){
$temp = array();
if($i%3 == 1){
$range = range($spl[$i], $spl[$i+1]);
$len = min(strlen($spl[$i]), strlen($spl[++$i]));
foreach($arr as $val){
foreach($range as $ran){
$temp[] = $val.str_pad($ran, $len, 0, 0);
}
}
}
else{
foreach($arr as $val){
$temp[] = $val.$spl[$i];
}
}
$arr = $temp;
}
$str = implode(PHP_EOL, $arr);
print($str);
It has the following result:
http://www.example.com/images/12.jpg
http://www.example.com/images/11.jpg
http://www.example.com/images/10.jpg
http://www.example.com/images/09.jpg
http://www.example.com/images/08.jpg
http://www.example.com/images/07.jpg
http://www.example.com/images/06.jpg
http://www.example.com/images/05.jpg
http://www.example.com/images/04.jpg
http://www.example.com/images/03.jpg
http://www.example.com/images/02.jpg
http://www.example.com/images/01.jpg

PHP :taking sub strings from given string

I have string in the following format.
Option1:Option2:Option3:Option4
I want to get these items separated and put it into a array.
array(item1=>option1,item2=>option2,item3=>option3,item4=>option4)
etc.
is there a straight forward way to get this done using regular expressions with PHP.
Thanks in advance for sharing your experience with me.
Use $arr = explode(":", $string); and then do this:
$result = array();
for ($i = 0; $i < count($arr); $i ++) {
$result['item' . $i] = $arr[$i];
}
and you should find $result to be exactly what you want
You can use explode function for that
$array = explode(":", $str);

Convert a string to an associative array

How would you convert a string like that to an associative array in PHP?
key1="value" key2="2nd value" key3="3rd value"
You could use a regular expression to get the key/value pairs:
preg_match_all('/(\w+)="([^"]*)"/', $str, $matches);
But this would just get the complete key/value pairs. Invalid input like key=value" would not get recognized. A parser would do better.
EDIT: Gumbo's answer is a better solution to this.
This any good to you?
Assume your string is in a variable like this:
$string = 'key1="value" key2="2nd value" key3="3rd value"';
First:
$array = explode('" ', $string);
you now have
array(0 => 'key1="value', 1=>'key2="2nd value', 2=>'key3="3rd value');
Then:
$result = array();
foreach ($array as $chunk) {
$chunk = explode('="', $chunk);
$result[$chunk[0]] = $chunk[1];
}
Using the regular expression suggested by Gumbo I came up with the following for converting the given string to an associative array:
$s = 'key1="value" key2="2nd value" key3="3rd value"';
$n = preg_match_all('/(\w+)="([^"]*)"/', $s, $matches);
for($i=0; $i<$n; $i++)
{
$params[$matches[1][$i]] = $matches[2][$i];
}
I was wondering if you had any comments.

Categories