What's the best way to accomplish the following.
I have strings in this format:
$s1 = "name1|type1"; //(pipe is the separator)
$s2 = "name2|type2";
$s3 = "name3"; //(in some of them type can be missing)
Let's assume nameN / typeN are strings and they can not contain a pipe.
Since I need to exctract the name / type separetly, I do:
$temp = explode('|', $s1);
$name = $temp[0];
$type = ( isset($temp[1]) ? $temp[1] : '' );
Is there an easier (smarter whatever faster) way to do this without having to do isset($temp[1]) or count($temp).
Thanks!
list($name, $type) = explode('|', s1.'|');
Note the order of arguments for explode()
list($name,$type) = explode( '|',$s1);
$type will be NULL for $s3, though it will give a Notice
I'm a fan of array_pop() and array_shift(), which don't error out if the array they use is empty.
In your case, that would be:
$temp = explode('|', $s1);
$name = array_shift($temp);
// array_shift() will return null if the array is empty,
// so if you really want an empty string, you can string
// cast this call, as I have done:
$type = (string) array_shift($temp);
There is not need to do isset since $temp[1] will exist and content an empty value. This works fine for me:
$str = 'name|type';
// if theres nothing in 'type', then $type will be empty
list($name, $type) = explode('|', $str, 2);
echo "$name, $type";
if(strstr($temp,"|"))
{
$temp = explode($s1, '|');
$name = $temp[0];
$type = $temp[1];
}
else
{
$name = $temp[0];
//no type
}
Maybe?
Related
i have these variables:
$pathPattern = '/catalog/{name}/{id}';
$pathRealUrl = '/catalog/test-product/12343';
The $pathPattern is dynamic, from a json file.
The $pathRealUrl is the url.
Now I need to create this two variables:
$name = 'test-product';
$id = 12343;
Note that the $pathPattern can have many variables
and also that {name} and {id} can have different name ( like {xxx} or {pippo} ), other sample:
$pathPattern = '/home/test/{hello}';
$pathRealUrl = '/home/test/alex';
The best way for archive this?
Split both string by / delimiter and loop through generated array from $pathPattern. In loop, get string that is between { and } and create variable named to it. At the end, set value of relevant index of $pathRealUrlArr in created variable.
$pathPatternArr = explode("/", $pathPattern);
$pathRealUrlArr = explode("/", $pathRealUrl);
foreach($pathPatternArr as $key=>$item){
if (preg_match("/^{(\w+)}$/", $item, $matches))
${$matches[1]} = $pathRealUrlArr[$key];
}
echo $name, $id;
See result in demo
You can shorten the code like bottom
foreach(explode("/", $pathPattern) as $key=>$item){
if (preg_match("/^{(\w+)}$/", $item, $matches))
${$matches[1]} = explode("/", $pathRealUrl)[$key];
}
echo $name, $id;
If the count of the number of values between the slashes will remain same or the position of the {name}/{id} will remain same then you can use explode to split the string by "/" and the get the desired values from the resultant array.
e.g.
$pathRealUrl = '/catalog/test-product/12343';
$array = explode("/",$pathRealUrl );
$id = $array[count($array)-1];
$name = $array[count($array)-2];
Ideone link : http://ideone.com/aNpxEJ
Hope it helps. :)
$pathPattern = '/catalog/{name}/{id}';
$pathRealUrl = '/catalog/test-product/12343';
$b = explode("/", $pathPattern);
$e = explode("/", $pathRealUrl);
$i = 0;
foreach ($b as $v) {
${substr($v,1,-1)} = $e[$i];
$i++;
}
echo $name;
echo $id;
And:
$i = 0;
foreach (explode("/", $pathPattern) as $v) {
${substr($v,1,-1)} = explode("/", $pathRealUrl)[$i];
$i++;
}
Show demo
My code:
$url = "http://www.google.com/test";
$parseurl = parse_url($url);
$explode = explode('.', $parseurl['host']);
$arrayreverse = array_reverse($explode);
foreach(array_values($arrayreverse) as $keyvalue) {
$result[] = $keyvalue;
}
$implode = implode('.', $result);
...
I'm interested to have values in one variable from $implode result and the result if isset the path from $parseurl... how can I do that ?
EDIT:
I want the values of $implode + and(if isset $parseurl['path']); to be in 1 variable but I can't figure out how to unite them.
Is ths what you want?
$newurl = $implode . (isset($parseurl['path']) ? $parseurl['path'] : '');
It uses the conditional operator to return either the path or an empty string, and concatenate that onto $implode.
I am creating a script that will locate a field in a text file and get the value that I need.
First used the file() function to load my txt into an array by line.
Then I use explode() to create an array for the strings on a selected line.
I assign labels to the array's to describe a $Key and a $Value.
$line = file($myFile);
$arg = 3
$c = explode(" ", $line[$arg]);
$key = strtolower($c[0]);
if (strpos($c[2], '~') !== false) {
$val = str_replace('~', '.', $c[2]);
}else{
$val = $c[2];
}
This works fine but that is a lot of code to have to do over and over again for everything I want to get out of the txt file. So I wanted to create a function that I could call with an argument that would return the value of $key and $val. And this is where I am failing:
<?php
/**
* #author Jason Moore
* #copyright 2014
*/
global $line;
$key = '';
$val = '';
$myFile = "player.txt";
$line = file($myFile); //file in to an array
$arg = 3;
$Character_Name = 3
function get_plr_data2($arg){
global $key;
global $val;
$c = explode(" ", $line[$arg]);
$key = strtolower($c[0]);
if (strpos($c[2], '~') !== false) {
$val = str_replace('~', '.', $c[2]);
}else{
$val = $c[2];
}
return;
}
get_plr_data2($Character_Name);
echo "This character's ",$key,' is ',$val;
?>
I thought that I covered the scope with setting the values in the main and then setting them a global within the function. I feel like I am close but I am just missing something.
I feel like there should be something like return $key,$val; but that doesn't work. I could return an Array but then I would end up typing just as much code to the the info out of the array.
I am missing something with the function and the function argument to. I would like to pass and argument example : get_plr_data2($Character_Name); the argument identifies the line that we are getting the data from.
Any help with this would be more than appreciated.
::Updated::
Thanks to the answers I got past passing the Array.
But my problem is depending on the arguments I put in get_plr_data2($arg) the number of values differ.
I figured that I could just set the Max of num values I could get but this doesn't work at all of course because I end up with undefined offsets instead.
$a = $cdata[0];$b = $cdata[1];$c = $cdata[2];
$d = $cdata[3];$e = $cdata[4];$f = $cdata[5];
$g = $cdata[6];$h = $cdata[7];$i = $cdata[8];
$j = $cdata[9];$k = $cdata[10];$l = $cdata[11];
return array($a,$b,$c,$d,$e,$f,$g,$h,$i,$j,$k,$l);
Now I am thinking that I can use the count function myCount = count($c); to either amend or add more values creating the offsets I need. Or a better option is if there was a way I could generate the return array(), so that it would could the number of values given for array and return all the values needed. I think that maybe I am just making this a whole lot more difficult than it is.
Thanks again for all the help and suggestions
function get_plr_data2($arg){
$myFile = "player.txt";
$line = file($myFile); //file in to an array
$c = explode(" ", $line[$arg]);
$key = strtolower($c[0]);
if (strpos($c[2], '~') !== false) {
$val = str_replace('~', '.', $c[2]);
}else{
$val = $c[2];
}
return array($key,$val);
}
Using:
list($key,$val) = get_plr_data2(SOME_ARG);
you can do this in 2 way
you can return both values in an array
function get_plr_data2($arg){
/* do what you have to do */
$output=array();
$output['key'] =$key;
$output['value']= $value;
return $output;
}
and use the array in your main function
you can use reference so that you can return multiple values
function get_plr_data2($arg,&$key,&$val){
/* do job */
}
//use the function as
$key='';
$val='';
get_plr_data2($arg,$key,$val);
what ever you do to $key in function it will affect the main functions $key
I was over thinking it. Thanks for all they help guys. this is what I finally came up with thanks to your guidance:
<?php
$ch_file = "Thor";
$ch_name = 3;
$ch_lvl = 4;
$ch_clss = 15;
list($a,$b)= get_char($ch_file,$ch_name);//
Echo $a,': ',$b; // Out Puts values from the $cdata array.
function get_char($file,$data){
$myFile = $file.".txt";
$line = file($myFile);
$cdata = preg_split('/\s+/', trim($line[$data]));
return $cdata;
}
Brand new to this community, thanks for all the patience.
I have a string that contains elements from array.
$str = '[some][string]';
$array = array();
How can I get the value of $array['some']['string'] using $str?
This will work for any number of keys:
$keys = explode('][', substr($str, 1, -1));
$value = $array;
foreach($keys as $key)
$value = $value[$key];
echo $value
You can do so by using eval, don't know if your comfortable with it:
$array['some']['string'] = 'test';
$str = '[some][string]';
$code = sprintf('return $array%s;', str_replace(array('[',']'), array('[\'', '\']'), $str));
$value = eval($code);
echo $value; # test
However eval is not always the right tool because well, it shows most often that you have a design flaw when you need to use it.
Another example if you need to write access to the array item, you can do the following:
$array['some']['string'] = 'test';
$str = '[some][string]';
$path = explode('][', substr($str, 1, -1));
$value = &$array;
foreach($path as $segment)
{
$value = &$value[$segment];
}
echo $value;
$value = 'changed';
print_r($array);
This is actually the same principle as in Eric's answer but referencing the variable.
// trim the start and end brackets
$str = trim($str, '[]');
// explode the keys into an array
$keys = explode('][', $str);
// reference the array using the stored keys
$value = $array[$keys[0][$keys[1]];
I think regexp should do the trick better:
$array['some']['string'] = 'test';
$str = '[some][string]';
if (preg_match('/\[(?<key1>\w+)\]\[(?<key2>\w+)\]/', $str, $keys))
{
if (isset($array[$keys['key1']][$keys['key2']]))
echo $array[$keys['key1']][$keys['key2']]; // do what you need
}
But I would think twice before dealing with arrays your way :D
I am using an api to retrieve data from another server the data returned is something like this:
accountid=10110 type=prem servertime=1263752255 validuntil=1266163393
username= curfiles=11 curspace=188374868 bodkb=5000000 premkbleft=24875313
This is a whole string I need two values out of whole string, I am currently using preg_match to get it, but just to learn more and improve my coding is there any other way or function in which all values are automatically convert to array?
Thank You.
Sooo, my faster-than-preg_split, strpos-based function looks like this:
function unpack_server_data($serverData)
{
$output = array();
$keyStart = 0;
$keepParsing = true;
do
{
$keyEnd = strpos($serverData, '=', $keyStart);
$valueStart = $keyEnd + 1;
$valueEnd = strpos($serverData, ' ', $valueStart);
if($valueEnd === false)
{
$valueEnd = strlen($serverData);
$keepParsing = false;
}
$key = substr($serverData, $keyStart, $keyEnd - $keyStart);
$value = substr($serverData, $valueStart, $valueEnd - $valueStart);
$output[$key] = $value;
$keyStart = $valueEnd + 1;
}
while($keepParsing);
return $output;
}
It looks for an equals character, then looks for a space character, and uses these two to decide where a key name begins, and when a value name begins.
Using explode is the fastest for this, no matter what.
However, to answer you question, you can do this many ways. But just because you can, doesn't mean you should. But if you really wanna make it weird, try this.
UPdated using strpos
$arr = array();
$begin = 0;
$str = trim($str); # remove leading and trailing whitespace
while ($end = strpos($str, ' ', $begin)) {
$split = strpos($str, '=', $begin);
if ($split > $end) break;
$arr[substr($str, $begin, $split-$begin)] = substr($str, $split+1, $end-$split-1);
$begin = $end+1;
}
try out parse_str maybe you need to do str_replace(' ', '&', $string); before