string slicing, php - php

is there a way to slice a string lets say i have this variable
$output=Country=UNITED STATES (US) &City=Scottsdale, AZ &Latitude=33.686 &Longitude=-111.87
i want to slice it in a way i want to pull latitude and longitude values in to seperate variables, subtok is not serving the purpose

You don't need a regular expression for this; use explode() to split up the string, first by &, and then by =, which you can use to effectively parse it into a nice little array mapping names to values.

$output='Country=UNITED STATES (US) &City=Scottsdale, AZ &Latitude=33.686 &Longitude=-111.87';
parse_str($output, $array);
$latitude = $array['latitude'];
You could also just do
parse_str($output);
echo $latitude;
I think using an array is better as you are not creating variables all over the place, which could potentially be dangerous (like register_globals) if you don't trust the input string.

It looks likes it's coming from an URL, although the URL encoding is gone.
I second the suggestions of using explode() or preg_split() but you might also be interested in parse_str().
$output = "City=Scottsdale, AZ &Latitude=33.686 &Longitude=-111.87";
parse_str($output, $results);
$lat = $results['Latitude'];
$lon = $results['Longitude'];

I'm not sure exactly what you're demonstrating in your code, maybe it's just some typos, is the "$output" the name of the variable, or part of the string?
Assuming it's the name of the variable, and you just forgot to put the quotes on the string, you have a couple options:
$sliced = explode('&', $output)
This will create an array with values: "Country=UNITED STATES(US) ", "City=Scottsdale, AZ ", etc.
$sliced = preg_split('/[&=]/', $output);
This will create an array with alternating elements being the "variables" and their values: "Country", "UNITED STATES(US) ", "City", "Scottsdale, AZ ", etc.

You could do the following:
$output = 'Country=UNITED STATES (US) &City=Scottsdale, AZ &Latitude=33.686 &Longitude=-111.87';
$strs = explode('&', $output);
foreach ($strs as $str) {
list($var, $val) = explode('=',$str);
$$var = trim($val);
}
This would give you variables such as $Latitude and $Longitude that are set to the value in the key/value pair.

All of the other Answers are Insufficient. This Should Work Every Time!
function slice($string, $start){
$st = $string; $s = $start; $l = strlen($st); $a = func_get_args();
$e = isset($a[2]) ? $a[2] : $l;
$f = $e-$s;
$p = $e < 0 && $s > 0 ? $l+$f : $f;
return substr($st, $s, $p);
}

I suggest you read about regular expressions in the PHP help.

Related

Content segregation from a Text string

I have this "&params=&offer=art-by-jeremy-johnson" stored in my data base.
Is there any function / method to get the output as "Art by Jeremy Johnson" using the above as the input value. this should be changed to the output "Art by Jeremy Johnson" only on the runtime.
can this be done in PHP.
Please help.
$orig = '&params=&offer=art-by-jeremy-johnson';
$parts = explode('=', $orig);
$output = explode('-', end($parts));
echo ucwords(implode(' ', $output));
In Java, I guess you can just use lastIndexOf to get the last index of the equals sign, and get the remainder of the string (using substring).
if (myString.lastIndexOf("=") != -1) {
String words = myString.substring(myString.lastIndexOf("=")+1);
words.replaceAll("-", " ");
return words;
}
$string="&params=&offer=art-by-jeremy-johnson";
parse_str($string,$output);
//print_r($output);
$str=ucwords(str_replace("-"," ",$output['offer']));
If I understand well you want to not capitalized some words.
Here is a way to do it :
$str = "&params=&offer=art-by-jeremy-johnson";
// List of words to NOT capitalized
$keep_lower = array('by');
parse_str($str, $p);
$o = explode('-', $p['offer']);
$r = array();
foreach ($o as $w) {
if (!in_array($w, $keep_lower))
$w = ucfirst($w);
$r[] = $w;
}
$offer = implode(' ', $r);
echo $offer,"\n";
output:
Art by Jeremy Johnson

Extract lat/long coordinates from a php string

I need to extract latitude and longitude coordinates from a string using php. The string will always be formatted as such:
"(42.32783298989135, -70.99989162915041)"
However the length of each value will vary from use to use. What's the best way to extract the values? Thanks!
You may use sscanf to do this:
sscanf($string, '"(%f, %f)"', $lat, $lng);
Test:
php > sscanf('"(42.32783298989135, -70.99989162915041)"', '"(%f, %f)"', $lat, $lng);
php > var_dump($lat, $lng);
float(42.327832989891)
float(-70.99989162915)
$withoutParentheses = substr($string, 1, -1);
$coordinates = explode(', ', $coordinates);
$longitude = floatval($coordinates[0]);
$latitude = floatval($coordinates[1]);
You could use a regular expression to extract the numbers from the brackets and then use the explode command to split the numbers into an array.
Your regex would be something like
/(-?[0-9]+.[0-9]+, -?[0-9]+.[0-9]+)/
and your delimiter for the explode command would be a comma.
This is what I came up with on my own:
function LatFromString($mCenterString){
//(42.32783298989135, -70.99989162915041)
$mLatLong = explode(",", $mCenterString);
$mLat = '';
if(count($mLatLong) == 2){
$mLat = substr($mLatLong[0], 1);
}
return $mLat;
}
function LongFromString($mCenterString){
//(42.32783298989135, -70.99989162915041)
$mLatLong = explode(",", $mCenterString);
$mLat = '';
if(count($mLatLong) == 2){
$mLong = substr($mLatLong[1], 0, -1);
}
return $mLong;
}
How does this look?
You could do something like this:
$str = "(42.32783298989135, -70.99989162915041)";
function extractlatlong($str){
$latlong = explode(",",$str);
if(count($latlong) == 2){
$lat = preg_replace("%[^0-9.]%","",$latlong[0]);
$long = preg_replace("%[^0-9.]%","",$latlong[1]);
return array("lat"=>$lat,"long"=>$long);
} else {
return NULL;
}
}
print_r(extractlatlong($str));
If you want to use sscanf() (and I probably would), but don't want to lose any precision from casting the numeric values as floats, then use a couple of negated character classes. You don't' have to match the trailing ) to extract what you need.
Code: (Demo)
$latlon = "(42.32783298989135, -70.99989162915041)";
sscanf($latlon, '(%[^,], %[^)]', $lat, $lon);
var_export([$lat, $lon]);
Output as an array of strings:
array (
0 => '42.32783298989135',
1 => '-70.99989162915041',
)
Or if you just want an indexed array of the two values like the above output:
var_export(sscanf($latlon, '(%[^,], %[^)]'));

String "array" to real array

Now I got the string of an array, like this :
$str = "array('a'=>1, 'b'=>2)";
How can I convert this string into real array ? Is there any "smart way" to do that, other that use explode() ? Because the "string" array could be very complicated some time.
Thanks !
Use php's "eval" function.
eval("\$myarray = $str;");
i don't know a good way to do this (only evil eval() wich realy should be avoided).
but: where do you get that string from? is it something you can affect? if so, using serialize() / unserialize() would be a much better way.
With a short version of the array json_decode works
json_decode('["option", "option2"]')
But with the old version just like the OP's asking it doesn't. The only thing it could be done is using Akash's Answer or eval which I don't really like using.
json_decode('array("option", "option2")')
You could write the string to a file, enclosing the string in a function definition within the file, and give the file a .php extension.
Then you include the php file in your current module and call the function which will return the array.
You'd have to use eval().
A better way to get a textual representation of an array that doesn't need eval() to decode is using json_encode() / json_decode().
If you can trust the string, use eval. I don't remember the exact syntax, but this should work.
$arr = eval($array_string);
If the string is given by user input or from another untrusted source, you should avoid eval() under all circumstances!
To store Arrays in strings, you should possibly take a look at serialize and unserialize.
Don't use eval() in any case
just call strtoarray($str, 'keys') for array with keys and strtoarray($str) for array which have no keys.
function strtoarray($a, $t = ''){
$arr = [];
$a = ltrim($a, '[');
$a = ltrim($a, 'array(');
$a = rtrim($a, ']');
$a = rtrim($a, ')');
$tmpArr = explode(",", $a);
foreach ($tmpArr as $v) {
if($t == 'keys'){
$tmp = explode("=>", $v);
$k = $tmp[0]; $nv = $tmp[1];
$k = trim(trim($k), "'");
$k = trim(trim($k), '"');
$nv = trim(trim($nv), "'");
$nv = trim(trim($nv), '"');
$arr[$k] = $nv;
} else {
$v = trim(trim($v), "'");
$v = trim(trim($v), '"');
$arr[] = $v;
}
}
return $arr;
}

Take a part of a string (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);

Array a string in the following format?

How can i array a string, in the format that $_POST does... kind of, well i have this kind of format coming in:
101=1&2020=2&303=3
(Incase your wondering, its the result of jQuery Sortable Serialize...
I want to run an SQL statement to update a field with the RIGHT side of the = sign, where its the left side of the equal sign? I know the SQL for this, but i wanted to put it in a format that i could use the foreach($VAR as $key=>$value) and build an sql statement from that.. as i dont know how many 101=1 there will be?
I just want to explode this in a way that $key = 101 and $value = 1
Sounds confusing ;)
Thanks so so much in advanced!!
See the parse_str function.
It's not the most intuitive function name in PHP but the function you're looking for is parse_str(). You can use it like this:
$myArray = array();
parse_str('101=1&2020=2&303=3', $myArray);
print_r($myArray);
One quick and dirty solution:
<?php
$str = "101=1&2020=2&303=3";
$VAR = array();
foreach(explode('&', $str) AS $pair)
{
list($key, $value) = each(explode('=', $pair));
$VAR[$key] = $value;
}
?>
parse_str($query_string, $array_to_hold_values);
$input = "101=1&2020=2&303=3";
$output = array();
$exp = explode('&',$input);
foreach($exp as $e){
$pair = explode("=",$e);
$output[$pair[0]] = $pair[1];
}
Explode on the & to get an array that contains [ 101=1 , 2020=2 , 303=3 ] then for each element, split on the = and push the key/value pair onto a new array.

Categories