string converting to array
<?php
$value1 = "Hello, world";
$convert = explode(" ",$value1);
echo $convert[1]; //Hello
echo $convert[2]; //world
// i convert particular number of array to string
$s = implode(" ", $convert[2]);
?>
I want output : world but I get this error message:
Error:
Warning: implode(): Invalid arguments passed in
I tried, but not done any one help
If you only want the output world, then this should work:
<?php
$value1 = "Hello, world";
$convert = explode(", ",$value1);
//echo $convert[0]; //Hello
echo $convert[1]; //world
?>
Related
I am using PHP 7.2.4, I want to make a template engine project,
I try to use preg_replace to change the variable in the string,
the code is here:
<?php
$lang = array(
'hello' => 'Hello {$username}',
'error_info' => 'Error Information : {$message}',
'admin_denied' => '{$current_user} are not Administrator',
);
$username = 'Guest';
$current_user = 'Empty';
$message = 'You are not member !';
$new_string = preg_replace_callback('/\{(\$[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*)\}/', 'test', $string);
function test($matches)
{
return '<?php echo '.$matches[1].'; ?>';
}
echo $new_string;
But it just show me
Hello , how are you?
It automatically remove the variable...
Update:
here is var_dump:
D:\Wamp\www\t.php:5:string 'Hello <?php echo $username; ?>, how are you?' (length=44)
You may use create an associative array with keys (your variables) and values (their values), and then capture the variable part after $ and use it to check in the preg_replace_callback callback function if there is a key named as the found capture. If yes, replace with the corresponding value, else, replace with the match to put it back where it was found.
Here is an example code in PHP:
$values = array('username'=>'AAAAAA', 'lastname'=>'Smith');
$string = 'Hello {$username}, how are you?';
$new_string = preg_replace_callback('/\{\$([a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*)}/', function($m) use ($values) {
return 'Hello <?php echo ' . (!empty($values[$m[1]]) ? $values[$m[1]] : $m[0]) . '; ?>';
}, $string);
var_dump($new_string);
Output:
string(47) "Hello Hello <?php echo AAAAAA; ?>, how are you?"
Note the pattern charnge, I moved the parentheses after $:
\{\$([a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*)}
^ ^
Actually, you may even shorten it to
\{\$([a-zA-Z_\x7f-\xff][\w\x7f-\xff]*)}
^^
Do you want something like this?
<?php
$string = 'Hello {$username}, how are you?';
$username = 'AAAAAA';
$new_string = preg_replace('/\{(\$[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*)\}/', $username, $string);
echo $new_string;
The result is:
Hello AAAAAA, how are you?
The more simple way would be to just write
<?php
$username = 'AAAAAA';
$string = 'Hello '.$username.', how are you?';
I'm a fan of keeping it simple so I would use str_replace since it will also change all instances which may come in handy as you go forward.
$string = 'Hello {$username}, how are you?';
$username = 'AAAAAA';
echo str_replace('{$username}',$username,$string);
I have a JSON structure as below
$json = '{"Number1":"{\"answerPhrase\":\"\\nTEXT,\\nTEXT
TEXT\\n\",\"dateUpdatedInMillisecond\":1234}"}';
When trying to extract the text and numbers I can do the first step and it works but the nested JSON has \\n and it does not give the text as output
The PHP code is as below
$result = json_decode($json);
print_r($result);
echo "<br>";
foreach($result as $key=>$value){
echo $key.$value;
echo "<br>";
$result_nest = json_decode($value);
echo $result_nest->answerPhrase;
echo "<br>";
Why can I not get the text in answerphrase? It works when the text does not have \\n
You may try the below one. You can replace the \n with some other characters. If you want to display enter in browser then you can replace \n with . Please try the below code and let me know if it worked for you.
<?php
$json = '{"Number1":"{\"answerPhrase\":\"\\nTEXT,\\nTEXT TEXT\\n\",\"dateUpdatedInMillisecond\":1234}"}';
$result = json_decode($json);
print_r($result);
echo "\n";
foreach($result as $key=>$value){
echo $key.$value;
echo "<br>";
$value = preg_replace("/\\n/", "___n___", $value);
$result_nest = json_decode($value);
$result_nest->answerPhrase = preg_replace("/___n___/", "\n", $result_nest->answerPhrase);
echo $result_nest->answerPhrase;
echo "<br>";
}
Prefer to fix json before decode and then decode the sub json.
you could do second step in a loop
function test2()
{
$string = '{"Number1":"{\"answerPhrase\":\"\\nTEXT,\\nTEXT
TEXT\\n\",\"dateUpdatedInMillisecond\":1234}"}';
$json = $this->decodeComplexJson($string);
$number = $json->Number1;
//Put this in a loop if you want
$decodedNumber = $this->decodeComplexJson($number);
var_dump($decodedNumber);
echo $decodedNumber->answerPhrase;
}
function decodeComplexJson($string) { # list from www.json.org: (\b backspace, \f formfeed)
$string = preg_replace("/[\r\n]+/", " ", $string);
$json = utf8_encode($string);
$json = json_decode($json);
return $json;
}
I have a variable that equals some simple data as shown below
$var = 'hello names here how are yous?';
what i wish to achieve is have a foreach loop inside the $var but i have tried various ways with just no luck, always throwing errors.
Below is somewhat what i what to do.
$var = 'hello '.foreach($datas as $data) { echo $data }.' how are yous?';
echo $var;
which would output - hello Mike Daniel Steve how are yous?
any help appreciated.
======EDIT========
im trying to write to file the looped contents with below code.
$datas = 'Name, Name2, Name4';
$var = ''.foreach($datas as $data) { echo $data }.'
$default_file = 'media/default.php';
$default_file_handle = fopen($default_file, 'w') or die('Cannot open file: '.$default_file);
$default_data = '
'.$var.'//each value to be a new line
Name2 //example
Name4 //example
etc
';
fwrite($default_file_handle, $default_data);
so basically im write to file each value in the loop to a new line. I can write just normal content but getting a loop in their im struggling with
$var = 'hello';
foreach($datas as $data) {
$var .= ' '.$data.' ';
}
$var .= ' how are you?';
echo $var;
that should do it
$arr = array("Mike", "John");
echo "Hello " . implode(" ", $arr) . ", how are you?";
implode is your friend. Implode joins array elements together into one single string. The separator between each array element is the first parameter - in this case a blank.
You can use implode:
$var = 'hello '.implode(' ', $datas) .' how are yous?';
echo $var;
To achieve this you either have to insert the foreach loop like this:
echo "hello ";
foreach($datas as $data) {
echo $data;
}
echo " how are you?";
or you can use an extra variable and the implode method:
$dataString = implode(" ", $datas);
echo "hello " . $dataString . " how are you?";
You can do this following way.
<?php
$data = array('Mike Daniel','john doe');
foreach ($data as $value) {
$result = 'hello '. $value. ' how are you?'. '</br>';
echo $result;
}
I'm trying to get a string with #hashtags and convert them into array keys!
For example:
string = "hello #world";
I want to replace to "hello $line['world']";
I did this:
$query = mysql_query($sql);
while($line = mysql_fetch_assoc($query)) {
$code = preg_replace("/(#(\w+))/", $line['$1'], $string);
echo $code;
}
But I get this warning: "Undefined index: $1" and obviously the echo prints only "hello "
But if I put a valid $line key directly it show its content. Like this:
$query = mysql_query($sql);
while($line = mysql_fetch_assoc($query)) {
$code = preg_replace("/(#(\w+))/", $line[name], $string);
echo $code;
}
It shows me "hello nameFromDatabase" for each line of database...
How can I set this $line[XXX] on the preg_replace to get the name located at the #hashtag replacement?
You can't with preg_replace. When you call that function you pass in two arguments:
"/(#(\w+))/"
$line['$1']
By the time preg is doing the replacement, it's already too late. The second argument has been evaluated and the preg_method cannot go back and re-evaulate the argument to what you want.
preg_replace_callback can do what you want though:
while($line = mysql_fetch_assoc($query)) {
$code = preg_replace_callback(
"/(#(\w+))/",
function($matches) use ($line) {
return $line[$matches[1]];
},
$string
);
echo $code;
}
I have this variable
$foo['title'] = 'Hello World';
I want to access this variable from a string.
$string = '$foo["title"]';
How can I display "Hello World" by my variable $string?
I searched an other topic, i found something similar, unfortunately it doesn't work.
$foo['title'] = "Hello, world!";
$bar = "foo['title']";
echo $$bar;
Actually I am not sure I understand you goal.
Do you want maybe this?
$foo['title'] = "Hello, world!";
$bar = "$foo[title]";
echo $bar;
The result:
Hello, world!
This is the same as this:
$bar = $foo['title'];
Or you would like to prepend/append something? Like this:
$bar = 'prepend something ' . $foo['title'] . ' append something';
You need to split the argument to the array away from the variable name, and then enclose the variable name in curly braces. So:
// get array argument
$matches = array();
preg_match("/\['(?s)(.*)'\]/", $bar, $matches);
$array_arg = $matches[1];
// get variable name
$arr = explode("[", $string, 2);
$var_name = $arr[0];
// put it together
${$var_name}[$array_arg]