I have a string that comes from a db: $text=
parameter1=value1
parameter2=value2
otherparemeter=othervalue
I need a function to replace an parameter with a new value, but if parameter does not exist; must to add to string;
Example: updatestring ($text,"parameter1","newvalue"):
Result:
parameter1=newvalue
parameter2=value2
otherparemeter=othervalue
Or: updatestring ($text,"myparameter","myvalue"):
Result:
parameter1=value1
parameter2=value2
otherparemeter=othervalue
myparameter=myvalue
thanks !
Given the format of your input parse_ini_string should work to parse out the data into a structure that can easily be altered and reformated.
Maybe something like this:
$a =<<<EOF
parameter1=value1
parameter2=value2
otherparemeter=othervalue
EOF;
function replacevalue($text, $k, $v){
$dat = parse_ini_string($text);
$ret = "";
if(isset($dat[$k])){
$dat[$k] = $v;
foreach($dat as $prop=>$val){
$ret.= $prop."=".$val."\n";
}
return $ret;
}
}
echo replacevalue($a, "parameter1", "Hello World");
this might work if every paramater and value are on its own line
function updatestring($text, $param1, $param2)
{
if( stristr($text, $param1.'=') ) $text = preg_replace("`$param1=.*\n`iU", "$param1=$param2".PHP_EOL, $text);
else $text .= PHP_EOL.$param1.'='.$param2;
return $text;
}
thanks #Orangepill; I've corrected your function; now it's working
function replacevalue($text, $k, $v){
$dat = parse_ini_string($text);
$ret = "";
if(isset($dat[$k])){
$dat[$k] = $v;
} else {
$dat[$k] = $v;
}
foreach($dat as $prop=>$val){
$ret.= $prop."=".$val."\n";
}
return $ret;
}
Related
I have this code that echoes values from an array. I'd like to be able to echo the variable elsewhere in my code though. I've tried wrapping a function around it and echoing the function but I can't get anything to work. Here's the code that I have now...
function team(){
if ( ($items = field_get_items('entityform', $entityform, 'field_team_members')) ) {
$values = array_map($items, function($x) { return $x['value']; });
$comma_separated = implode(', ', $values);
foreach ($items as $item) {
$members = $prefix . $item['safe_value'];
$prefix = ', ';
echo $members;
}
}
}
If I simply do team(); it outputs nothing, as well as echo team();. What am I doing wrong here?
Your team function doesn't return anything which is why echo team(); doesn't print anything.
See the documentation on functions for more info: http://php.net/manual/en/functions.returning-values.php
function team(){
$output = '';
if ( ($items = field_get_items('entityform', $entityform, 'field_team_members')) ) {
$values = array_map($items, function($x) { return $x['value']; });
$comma_separated = implode(', ', $values);
$prefix = '';
$members = '';
foreach ($items as $item) {
$members .= $prefix . $item['safe_value'];
$prefix = ', ';
}
$output = $members;
}
return $output;
}
To clarify what i wrote as a comment, i just created a small script:
<?php
function team () {
$string = "hi";
return $string;
}
echo team();
Functions cant work unless until they are called, so you have to call team(); in some way, once called it will for sure display what ever you are trying to echo. Also above function will not display anything unless you force fully exit in that function. Or return some value.
I have the following text string: "Gardening,Landscaping,Football,3D Modelling"
I need PHP to pick out the string before the phrase, "Football".
So, no matter the size of the array, the code will always scan for the phrase 'Football' and retrieve the text immediately before it.
Here is my (lame) attempt so far:
$array = "Swimming,Astronomy,Gardening,Rugby,Landscaping,Football,3D Modelling";
$find = "Football";
$string = magicFunction($find, $array);
echo $string; // $string would = 'Landscaping'
Any help with this would be greatly appreciated.
Many thanks
$terms = explode(',', $array);
$index = array_search('Football', $terms);
$indexBefore = $index - 1;
if (!isset($terms[$indexBefore])) {
trigger_error('No element BEFORE');
} else {
echo $terms[$indexBefore];
}
//PHP 5.4
echo explode(',Football', $array)[0]
//PHP 5.3-
list($string) = explode(',Football', $array);
echo $string;
$array = array("Swimming","Astronomy","Gardening","Rugby","Landscaping","Football","3D" "Modelling");
$find = "Football";
$string = getFromOffset($find, $array);
echo $string; // $string would = 'Landscaping'
function getFromOffset($find, $array, $offset = -1)
{
$id = array_search($find, $array);
if (!$id)
return $find.' not found';
if (isset($array[$id + $offset]))
return $array[$id + $offset];
return $find.' is first in array';
}
You can also set the offset to be different from 1 previous.
Having a string like
12345.find_user.find_last_name
how can i split at the charachter "." and convert it to a function-call:
find_last_name(find_user(12345));
and so on....could be of N-Elements (n-functions to run)....how do i do this effectivly, performance-wise also?
Edit, here is the solution based on your replies
thanks Gaurav for your great help. Here is my complete solution based on yours:
i protected the foreach with if(function_exists($function)){ to protect the whole thing from fatal php errors, and i added a complete example:
$mystring = '12345.find_user.find_last_name';
convert_string_to_functions($mystring);
function convert_string_to_functions($mystring){
$functions = explode('.', $mystring);
$arg = array_shift($functions);
foreach($functions as $function){
if(function_exists($function)){
$arg = $function($arg);
} else {
echo 'Function '.$function.' Not found';
}
}
echo $arg;
}
function find_last_name($mystring=''){
return $mystring.' i am function find_last_name';
}
function find_user($mystring=''){
return $mystring.' i am function find_user';
}
$string = '12345.find_user.find_last_name';
$functions = explode('.', $string);
$arg = array_shift($functions);
foreach($functions as $function){
$arg = $function($arg);
}
echo $arg;
I want to convert a big yaml file to PHP array source code. I can read in the yaml code and get back a PHP array, but with var_dump($array) I get pseudo code as output. I would like to print the array as valid php code, so I can copy paste it in my project and ditch the yaml.
You're looking for var_export.
You could use var_export, serialize (with unserialize on the reserving end), or even json_encode (and use json_decode on the receiving end). The last one has the advantage of producing output that can be processed by anything that can handle JSON.
Don't know why but I could not find satisfying code anywhere.
Quickly wrote this. Let me know if you find any errors.
function printCode($array, $path=false, $top=true) {
$data = "";
$delimiter = "~~|~~";
$p = null;
if(is_array($array)){
foreach($array as $key => $a){
if(!is_array($a) || empty($a)){
if(is_array($a)){
$data .= $path."['{$key}'] = array();".$delimiter;
} else {
$data .= $path."['{$key}'] = \"".htmlentities(addslashes($a))."\";".$delimiter;
}
} else {
$data .= printCode($a, $path."['{$key}']", false);
}
}
}
if($top){
$return = "";
foreach(explode($delimiter, $data) as $value){
if(!empty($value)){
$return .= '$array'.$value."<br>";
}
};
return $return;
}
return $data;
}
//REQUEST
$x = array('key'=>'value', 'key2'=>array('key3'=>'value2', 'key4'=>'value3', 'key5'=>array()));
echo printCode($x);
//OUTPUT
$array['key'] = 'value';
$array['key2']['key3'] = 'value2';
$array['key2']['key4'] = 'value3';
$array['key2']['key5'] = array();
Hope this helps someone.
An other way to display array as code with indentation.
Tested only with an array who contain string, integer and array.
function bo_print_nice_array($array){
echo '$array=';
bo_print_nice_array_content($array, 1);
echo ';';
}
function bo_print_nice_array_content($array, $deep=1){
$indent = '';
$indent_close = '';
echo "[";
for($i=0; $i<$deep; $i++){
$indent.=' ';
}
for($i=1; $i<$deep; $i++){
$indent_close.=' ';
}
foreach($array as $key=>$value){
echo "<br>".$indent;
echo '"'.$key.'" => ';
if(is_string($value)){
echo '"'.$value.'"';
}elseif(is_array($value)){
bo_print_nice_array_content($value, ($deep+1));
}else{
echo $value;
}
echo ',';
}
echo '<br>'.$indent_close.']';
}
If I had an array such as:
testarray = array('foo'=>34, 'bar'=>array(1, 2, 3));
How would I go about converting a string such as testarray[bar][0] to find the value its describing?
Well, you can do something like this (Not the prettiest, but far safer than eval)...:
$string = "testarray[bar][0]";
$variableBlock = '[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*';
$regex = '/^('.$variableBlock.')((\[\w+\])*)$/';
if (preg_match($regex, $string, $match)) {
$variableName = $match[1]; // "testarray"
if (!isset($$variableName)) {
//Error, the variable does not exist
return null;
} else {
$array = $$variableName;
if (preg_match_all('/\[(\w+)\]/', $match[2], $matches)) {
foreach ($matches[1] as $match) {
if (!is_array($array)) {
$array = null;
break;
}
$array = isset($array[$match]) ? $array[$match] : null;
}
}
return $array;
}
} else {
//error, not in correct format
}
You could use PHP's eval function.
http://php.net/manual/en/function.eval.php
However, make absolutely sure the input is sanitized!
Cheers