I need to broke a string into some vars but its order is not fixed as the exemple:
$string = "name='John';phone='555-5555';city='oakland';";
$string2 = "city='oakland';phone='555-5555';name='John';";
$string3 = "phone='555-5555';name='John';city='oakland';";
so I need to broke the strings into:
$name
$phone
$city
if the position would be fixed i could use explode and call for the array key that i need like
$brokenString = explode("'",$string);
$name = $brokenString[1];
$phone = $brokenString[3];
$city = $brokenString[5];
however how could I do it with variable position??
One way to do it with sort to make the position same always for all string variables.
<?php
$string = "name='John';phone='555-5555';city='oakland';";
$string2 = "city='oakland';phone='555-5555';name='John';";
$string3 = "phone='555-5555';name='John';city='oakland';";
$array = explode(';',$string3);
sort($array);
$array = array_filter($array); # remove the empty element
foreach($array as $value){
$split = explode('=',$value);
$result[$split[0]] = $split[1];
}
extract($result); # extract result as php variables
echo "\$city = $city; \$name = $name; \$phone = $phone";
?>
EDIT: As using extract() is generally not a good idea.You can use simple foreach() instead of extract(),
foreach($result as $k => $v) {
$$k = $v;
}
WORKING DEMO: https://3v4l.org/RB8pT
There might be a simpler method, but what I've done is created an array $stringVariables which holds the exploded strings.
This array is then looped through and strpos is used in each element in the exploded string array to see if it contains 'city', 'phone', or 'name'. Depending on which one, it's added to an array which holds either all the names, cities or phone numbers.
$stringVariables = array();
$phones = array();
$names = array();
$cities = array();
$stringVariables[] = explode(";",$string);
$stringVariables[] = explode(";",$string2);
$stringVariables[] = explode(";",$string3);
foreach($stringVariables as $stringVariable) {
foreach($stringVariable as $partOfString) {
if(strpos($partOfString, "name=") !== false) {
$names[] = $partOfString;
}else if(strpos($partOfString, "city=") !== false) {
$cities[] = $partOfString;
}else if(strpos($partOfString, "phone=") !== false) {
$phones[] = $partOfString;
}
}
}
An alternative way is to convert it into something that can be parsed as a URL string.
First part is to change the values and , from 'John', to John& using a regex ('([^']+)'; which looks for a ' up to a ' followed by a ;), then parse the result (using parse_str())...
$string = "name='John';phone='555-5555';city='oakland';";
$string = preg_replace("/'([^']+)';/","$1&", $string);
echo $string.PHP_EOL;
parse_str( $string, $values );
print_r($values);
gives the output of
name=John&phone=555-5555&city=oakland&
Array
(
[name] => John
[phone] => 555-5555
[city] => oakland
)
or just using regex's...
preg_match_all("/(\w*)?='([^']+)';/", $string, $matches);
print_r(array_combine($matches[1], $matches[2]));
Related
I have below small PHP script, I just need the value from the array if I provide key in $str.
$empid_array = array('CIP004 - Rinku Yadav', 'CIP005 - Shubham Sehgal');
$key = array();
$value = array();
$str = "CIP004";
foreach($empid_array as $code){
$str = preg_split("/\-/", $code);
array_push($key, $str[0]);
array_push($value, $str[1]);
}
$combined = array_combine($key, $value);
echo count($combined);
foreach($combined as $k => $v){
if($str == $k){
echo $v;
}
}
You could simplify your code considerably here. Step one, use array_walk to walk through the array and build the $combined array. Step two, there's no point in looping through the array, just access the value by the index:
$empid_array = ['CIP004 - Rinku Yadav', 'CIP005 - Shubham Sehgal'];
$str = "CIP004";
$combined = [];
// passing $combined by reference so we can modify it
array_walk($empid_array, function ($e) use (&$combined) {
list($id, $name) = explode(" - ", $e);
$combined[$id] = $name;
});
echo $combined[$str] ?? "Not found";
I have custom cms database and get parameter from database and my result this is:
$param = 'param1="value1"|param2="value2"|param3="value3"|param4="value4"|param5="value5"'
but I need get param1 value or other value. I try use explode but my result this is:
$string = explode('|',$param);
result:
array (size=4)
0 => string 'param1="value1"'
1 => string 'param2="value2"'
2 => string 'param3="value3"'
3 => string 'param4="value4"'
4 => string 'param5="value4"'
I need get value this format:
$param->param1 = value1;
You also need to explode each of the substrings on =, and then map the results into an array:
$param = 'param1="value1"|param2="value2"|param3="value3"|param4="value4"|param5="value5"';
$params = explode('|', $param);
$results = [];
foreach ($params as $element) {
list($key, $value) = explode('=', $element, 2);
$results[$key] = json_decode($value);
}
echo $results['param1']; // value1
The call to json_decode might look a bit out of place here, but it's the quickest way to convert a quoted string into a native PHP string. The additional argument to the second explode call is to limit the result to two variables, in case the value itself contains an equals sign.
Try parse_str, you can then create an object using the array
<?php
$param = 'param1="value1"|param2="value2"|param3="value3"|param4="value4"|param5="value5"';
$params = array();
parse_str(str_replace('|', '&', $param), $params);
$params = (object) $params;
echo $params->param1;
?>
Nice and easy with a litte regex:
$param = 'param1="value1"|param2="value2"|param3="value3"|param4="value4"|param5="value5"';
$strings = explode('|', $param);
foreach ($strings as $string) {
preg_match('#param\d="(?<value>.+)"#', $string, $matches);
var_dump($matches['value']);
}
The regex #param\d="(?<value>.+)"# looks for param followed by a number then an equals, and we create a named capture group with ?<value> in the brackets.
The output from the var_dumps looks like this:
string(6) "value1"
string(6) "value2"
string(6) "value3"
string(6) "value4"
string(6) "value5"
Try it here https://3v4l.org/bomO7
When you've split the first part using '|', you can convert the rest as though it was a CSV field with '=' as the divider. This deals with quotes and other elements.
<?php
error_reporting ( E_ALL );
ini_set ( 'display_errors', 1 );
$param = 'param1="value1"|param2="value2"|param3="value3"|param4="value4"|param5="value5"';
$parms = explode('|', $param );
$values = [];
foreach ( $parms as $parm ) {
list($key, $value) = str_getcsv($parm, "=");
$values[$key] = $value;
}
print_r($values);
$param = 'param1="value1"|param2="value2"|param3="value3"|param4="value4"|param5="value5"';
$param = json_decode('{"' . str_replace(['=', '|'], ['":', ',"'], $param) . '}');
print_r($param);
This is just example. Don't use it in production :)
Use the following approach:
$param = 'param1="value1"|param2="value2"|param3="value3"|param4="value4"|param5="value5"';
$result = [];
foreach (explode('|', $param) as $item) {
list($k,$v) = explode('=', $item);
$result[$k] = trim($v, '"');
}
$result = (object) $result;
// as you wanted
print_r($result->param1); // value1
I have seen a bunch of ways, but none that seem to work. My array data is coming back like this.
Array
(
[0] => RESULT=0
[1] => RESPMSG=Approved
[2] => SECURETOKEN=8cpcwfZhaH02qNlIoFEGZ1wO4
[3] => SECURETOKENID=253cad735251571cebcea28e877f4fd7
I use this:
<?php echo $response[2];?>
too get each out, that works. But I need to remove “SECURETOKEN=” so im left with just the number strings. I have been trying something like this with out success.
function test($response){
$secure_token = $response[1];
$secure_token = substr($secure_token, -25);
return $secure_token;
}
Also Im putting end number into a form input “Value” field. Not that that matters, unless it does?
Thanks
This is what I would do:
$keyResponse = [];
foreach ($response as $item) {
list($k, $v) = explode('=', $item, 2);
$keyResponse[$k] = $v;
}
Now you can easily access just the value part of each item based on the name:
echo $keyResponse['SECURETOKEN']; // output: 8cpcwfZhaH02qNlIoFEGZ1wO4
The advantage to this method is the code still works if the order of the items in $response changes
I get your secure token like this (tested):
<?php
$arr = array(
'RESULT=0',
'RESPMSG=Approved',
'SECURETOKEN=8cpcwfZhaH02qNlIoFEGZ1wO4',
'SECURETOKENID=253cad735251571cebcea28e877f4fd7'
);
$el = $arr[2];
$parts = explode('=', $el);
echo '#1 SECURETOKEN is ' . $parts[1];
// This break just for testing
echo '<br />';
// If you wanted to, you could revise the whole array
$new = array();
foreach( $arr as $el ){
$parts = explode('=', $el);
$new[$parts[0]] = $parts[1];
}
// Which would mean you could then get your securetoken like this:
echo '#2 SECURETOKEN is ' . $new['SECURETOKEN'];
I have a web service to identify people and their functions from an external database that returns me a set of data if the login is successful. The data (that interests me right now) is separated in different strings as follow:
$groups="group1, group2, group3"
$functions="member, member, admin"
The first element of the string $groups corresponds to the first element of the $functions string.
We can have empty spots in the strings:
$groups="group1,, group3";
$functions="member,, admin";
What is the best way to combine them to obtain:
$usertype(
group1=>member,
group2=>member,
group3=>admin,
);
Then I plan to use array_search() to get the name of the group that corresponds to a function.
This is very trick especially when the first element is empty but here is a comprehensive solution
What you need is :
// Your Varriables
$groups = "group1,, group3";
$functions = "member,, admin";
// Break Into Array
$groups = explode(",", $groups);
$functions = explode(",", $functions);
// Combine both new Arrays and Output Result
$new = array_combine($groups, $functions);
print_r($new);
If you need to fix null values then :
Example :
// Your Varriables
$groups = "group1,, group3";
$functions = "member,, admin";
// Break Into Array
$groups = explode(",", $groups);
$functions = explode(",", $functions);
// Fix Null Values
$groups = fixNull($groups, true);
$functions = fixNull($functions);
// Combine both new Arrays and Output Result
$new = array_combine($groups, $functions);
print_r($new);
Output
Array
(
[group1] => member
[group2] => member
[group3] => admin
)
See Live DEMO
More Complex:
// Your Varriables
$groups = ",,, group3";
$functions = ",member,, admin";
// Fix Null Values
$groups = fixNull(explode(",", $groups), true);
$functions = fixNull(explode(",", $functions));
// Combine both new Arrays and Output Result
$new = array_combine($groups, $functions);
print_r($new);
Output
Array
(
[group4] => member
[group5] => member
[group6] => member
[group3] => admin
)
Live DEMO
Function Used
function fixNull($array, $inc = false) {
$ci = new CachingIterator(new ArrayIterator($array), CachingIterator::FULL_CACHE);
if ($inc) {
$next = array_filter($array);
$next = current($next);
$next ++;
} else {
$next = array_filter($array);
sort($next);
$next = end($next);
}
$next || $next = null;
$modified = array();
foreach($ci as $item) {
$modified[] = empty($item) ? trim($next) : trim($item);
if (! $ci->getInnerIterator()->current()) {
$item || $item = $next;
$next = $inc ? ++ $item : $item;
}
}
return $modified;
}
$groups = explode(",", $groups);
$functions = explode(",", $functions);
//then use the elements of the $groups array as key and the elements of the $functions array as the value
$merged = array_combine($groups, $functions);
Something along the lines of this should help:
$usertype = array_combine(explode(',', $groups), explode(',', $functions));
Use explode() to make arrays of your strings, and array_combine() to use one array as keys, the other one as values.
$groups = "group1, group2, group3";
$functions = "member, member, admin";
$usertype = array_combine(explode(", ", $groups), explode(", ", $functions));
Have you tried a explode($delimiter , $string) and then filter the array? I think that would be a good way of doing it:
$groups="group1,, group3";
$functions="member,, admin";
$groups_array = array_map('trim',explode(',', $groups));
$functions_array = array_map('trim',explode(',', $functions));
$final = array();
for ($i = 0; $i <= count($groups_array); $i++) {
$final[$groups_array[$i]] = $functions_array[$i];
}
$merged = array_combine($groups_array, $functions_array);
Demo
$groups="group1, group2, group3"
$functions="member, member, admin"
preg_match_all('/\w+/', $groups, $groups);
preg_match_all('/\d+/', $functions, $functions);
$final = array();
foreach ($groups[0] AS $key => $letter)
$final[] = $letter . '=>' . $functions[0][$key];
echo join(', ', $final);
explode and array_combine.
Note that you have a problem with whitespaces. Therefore use the following:
<?php
$groups="group1, group2, group3";
$functions="member, member, admin";
$groupArray = array_map(function($element){return trim($element);},
explode(',',$groups)); // split into array and remove leading and ending whitespaces
$functionArray = array_map(function($element){return trim($element);},
explode(',',$functions)); // split into array and remove leading and ending whitespaces
print_r(array_combine($groupArray,$functionArray));
?>
This will output:
Array
(
[group1] => member
[group2] => member
[group3] => admin
)
EDIT: removed trim for the possibility that the first element is empty.
Let's say I have this:
$array = array("john" => "doe", "foe" => "bar", "oh" => "yeah");
foreach($array as $i=>$k)
{
echo $i.'-'.$k.',';
}
echoes "john-doe,foe-bar,oh-yeah,"
How do I get rid of the last comma?
Alternatively you can use the rtrim function as:
$result = '';
foreach($array as $i=>$k) {
$result .= $i.'-'.$k.',';
}
$result = rtrim($result,',');
echo $result;
I dislike all previous recipes.
Php is not C and has higher-level ways to deal with this particular problem.
I will begin from the point where you have an array like this:
$array = array('john-doe', 'foe-bar', 'oh-yeah');
You can build such an array from the initial one using a loop or array_map() function. Note that I'm using single-quoted strings. This is a micro-optimization if you don't have variable names that need to be substituted.
Now you need to generate a CSV string from this array, it can be done like this:
echo implode(',', $array);
One method is by using substr
$array = array("john" => "doe", "foe" => "bar", "oh" => "yeah");
$output = "";
foreach($array as $i=>$k)
{
$output .= $i.'-'.$k.',';
}
$output = substr($output, 0, -1);
echo $output;
Another method would be using implode
$array = array("john" => "doe", "foe" => "bar", "oh" => "yeah");
$output = array();
foreach($array as $i=>$k)
{
$output[] = $i.'-'.$k;
}
echo implode(',', $output);
I don't like this idea of using substr at all, since it's the style of bad programming. The idea is to concatenate all elements and to separate them by special "separating" phrases. The idea to call the substring for that is like to use a laser to shoot the birds.
In the project I am currently dealing with, we try to get rid of bad habits in coding. And this sample is considered one of them. We force programmers to write this code like this:
$first = true;
$result = "";
foreach ($array as $i => $k) {
if (!$first) $result .= ",";
$first = false;
$result .= $i.'-'.$k;
}
echo $result;
The purpose of this code is much clearer, than the one that uses substr. Or you can simply use implode function (our project is in Java, so we had to design our own function for concatenating strings that way). You should use substr function only when you have a real need for that. Here this should be avoided, since it's a sign of bad programming style.
I always use this method:
$result = '';
foreach($array as $i=>$k) {
if(strlen($result) > 0) {
$result .= ","
}
$result .= $i.'-'.$k;
}
echo $result;
try this code after foreach condition then echo $result1
$result1=substr($i, 0, -1);
Assuming the array is an index, this is working for me. I loop $i and test $i against the $key. When the key ends, the commas do not print. Notice the IF has two values to make sure the first value does not have a comma at the very beginning.
foreach($array as $key => $value)
{
$w = $key;
//echo "<br>w: ".$w."<br>";// test text
//echo "x: ".$x."<br>";// test text
if($w == $x && $w != 0 )
{
echo ", ";
}
echo $value;
$x++;
}
this would do:
rtrim ($string, ',')
see this example you can easily understand
$name = ["sumon","karim","akash"];
foreach($name as $key =>$value){
echo $value;
if($key<count($name){
echo ",";
}
}
I have removed comma from last value of aray by using last key of array. Hope this will give you idea.
$last_key = end(array_keys($myArray));
foreach ($myArray as $key => $value ) {
$product_cateogry_details="SELECT * FROM `product_cateogry` WHERE `admin_id`='$admin_id' AND `id` = '$value'";
$product_cateogry_details_query=mysqli_query($con,$product_cateogry_details);
$detail=mysqli_fetch_array($product_cateogry_details_query);
if ($last_key == $key) {
echo $detail['product_cateogry'];
}else{
echo $detail['product_cateogry']." , ";
}
}
$foods = [
'vegetables' => 'brinjal',
'fruits' => 'orange',
'drinks' => 'water'
];
$separateKeys = array_keys($foods);
$countedKeys = count($separateKeys);
for ($i = 0; $i < $countedKeys; $i++) {
if ($i == $countedKeys - 1) {
echo $foods[$separateKeys[$i]] . "";
} else {
echo $foods[$separateKeys[$i]] . ", \n";
}
}
Here $foods is my sample associative array.
I separated the keys of the array to count the keys.
Then by a for loop, I have printed the comma if it is not the last element and removed the comma if it is the last element by $countedKeys-1.