How to get an array from string, containing an array? - php

Is it possible to using a regular expression, or otherwise create a function that will convert a string containing the php array of any form, in the real array, which can operate?
For Example:
$str = "array(1, array(2), array('key' => 'value'))";
$arr = stringArrayToArray($str);
Maybe there is already such an implementation of task?
Or do not bother, but simply to use eval()?
$arr = eval("return $str;");

You can try explode() function.
Try it.
<?php
$str = "do you love me";
$arr = explode(' ', $str);
print_r($arr);
?>

You can just replace the array( with a [ and ) with ]
as shown below:
$str = "array(1, array(2), array('key' => 'value'))";
$str = str_replace(" ","",str_replace(",","[",$str));
$str = str_replace(")","",str_replace("array(","[",$str));
echo $str;
$arr = explode("[",$str);
var_dump($arr);
?>
this the best I could get.

Related

Replace with dynamic variable in preg_replace

I'm getting stuck at this problem, which is
I have an array like this:
$array = [
'name' => 'John',
'email' => john#gmail.com
];
And a string sample like this:
$string = 'Hi [[name]], your email is [[email]]';
The problem is obvious, replace name with John and email with john#gmail.com.
What i attempted:
//check if $string has [[ ]] pattern
$stringHasBrackets = preg_match_all('/\[\[(.*?)\]\]/i', $string, $matchOutput);
if ($stringHasBrackets) {
foreach ($matchOutput[1] as $matchOutputKey => $stringToBeReplaced) {
if (array_key_exists($stringToBeReplaced, $array)) {
$newString = preg_replace("/\[\[(.+?)\]\]/i",
$array[$stringToBeReplaced],
$string);
}
}
}
Which led me to a new string like this:
Hi john#gmail.com, your email is john#gmail.com
Makes sense because that's what the pattern is for, but not what I wanted.
How can I solve this? I thought of using a variable in the pattern but don't know how to do it. I've read about preg_replace_callback but also don't really know how to implement it.
Thanks!
You may use preg_replace_callback like this:
$array = ['name' => 'John', 'email' => 'john#gmail.com'];
$string = 'Hi [[name]], your email is [[email]]';
echo preg_replace_callback('/\[\[(.*?)]]/', function ($m) use ($array) {
return isset($array[$m[1]]) ? $array[$m[1]] : $m[0];
}, $string);
See PHP demo.
Details
'/\[\[(.*?)]]/' matches [[...]] substrings putting what is inside the brackets into Group 1
$m holds the match object
use ($array) allows the callback to access $array variable
isset($array[$m[1]]) checks if there is a value corresponding to the found key in the $array variable. If it is found, the value is returned, else, the found match is pasted back.
preg_replace accepts arrays as regex and replacement so you can use this simpler approach:
$array = ['name' => 'John', 'email' => 'john#gmail.com'];
$string = 'Hi [[name]], your email is [[email]]';
// create array of regex using array keys
$rearr = array_map(function($k) { return '/\[\[' . $k . ']]/'; },
array_keys($array));
# pass 2 arrays to preg_replace
echo preg_replace($rearr, $array, $string) . '\n';
Output:
Hi John, your email is john#gmail.com
PHP Code Demo
You can try this,
$array = ['name' => 'John', 'email' => 'john#gmail.com'];
$string = 'Hi [[name]], your email is [[email]]';
$stringHasBrackets = preg_match_all('/\[\[(.*?)\]\]/i', $string, $matchOutput);
if ($stringHasBrackets) {
$newString = $string;
foreach ($matchOutput[1] as $matchOutputKey => $stringToBeReplaced) {
if (array_key_exists($stringToBeReplaced, $array)) {
$newString = preg_replace("/\[\[$stringToBeReplaced\]\]/i", $array[$stringToBeReplaced], $newString);
}
}
echo $newString;
}
I think here more simply would be to use str_replace function, like:
$array = [
'name' => 'John',
'email' => 'john#gmail.com'
];
$string = 'Hi [[name]], your email is [[email]]';
$string = str_replace(array_map(function ($v) {return "[[{$v}]]";},
array_keys($array)), $array, $string);
echo $string;
Updated for $array to be "untouchable"

php replace all occurances of key from array in string

maybe this is duplicate but i did't find good solution.
I have array
$list = Array
(
[hi] => 0
[man] => 1
);
$string="hi man, how are you? man is here. hi again."
It should produce $final_string = "0 1, how are you? 1 is here. 0 again."
How can I achieve it with smart way? Many thanks.
Off of the top of my head:
$find = array_keys($list);
$replace = array_values($list);
$new_string = str_ireplace($find, $replace, $string);
Can be done in one line using strtr().
Quoting the documentation:
If given two arguments, the second should be an array in the form array('from' => 'to', ...). The return value is a string where all the occurrences of the array keys have been replaced by the corresponding values. The longest keys will be tried first. Once a substring has been replaced, its new value will not be searched again.
To get the modified string, you'd just do:
$newString = strtr($string, $list);
This would output:
0 1, how are you? 1 is here. 0 again.
Demo.
$text = strtr($text, $array_from_to)
See http://php.net/manual/en/function.strtr.php
preg_replace may be helpful.
<?php
$list = Array
(
'hi' => 0,
'man' => 1
);
$string="hi man, how are you? Man is here. Hi again.";
$patterns = array();
$replacements = array();
foreach ($list as $k => $v)
{
$patterns[] = '/' . $k . '/i'; // use i to ignore case
$replacements[] = $v;
}
echo preg_replace($patterns, $replacements, $string);

How to convert array to a string using methods other than JSON?

What is a function in PHP used to convert array to string, other than using JSON?
I know there is a function that directly does like JSON. I just don't remember.
serialize() is the function you are looking for. It will return a string representation of its input array or object in a PHP-specific internal format. The string may be converted back to its original form with unserialize().
But beware, that not all objects are serializable, or some may be only partially serializable and unable to be completely restored with unserialize().
$array = array(1,2,3,'foo');
echo serialize($array);
// Prints
a:4:{i:0;i:1;i:1;i:2;i:2;i:3;i:3;s:3:"foo";}
Use the implode() function:
$array = array('lastname', 'email', 'phone');
$comma_separated = implode(",", $array);
echo $comma_separated; // lastname,email,phone
readable output!
echo json_encode($array); //outputs---> "name1":"value1", "name2":"value2", ...
OR
echo print_r($array, true);
You are looking for serialize(). Here is an example:
$array = array('foo', 'bar');
//Array to String
$string = serialize($array);
//String to array
$array = unserialize($string);
Another good alternative is http_build_query
$data = array('foo'=>'bar',
'baz'=>'boom',
'cow'=>'milk',
'php'=>'hypertext processor');
echo http_build_query($data) . "\n";
echo http_build_query($data, '', '&');
Will print
foo=bar&baz=boom&cow=milk&php=hypertext+processor
foo=bar&baz=boom&cow=milk&php=hypertext+processor
More info here http://php.net/manual/en/function.http-build-query.php
use php implode() or serialize()
Display array in beautiful way:
function arrayDisplay($input)
{
return implode(
', ',
array_map(
function ($v, $k) {
return sprintf("%s => '%s'", $k, $v);
},
$input,
array_keys($input)
)
);
}
$arr = array('foo'=>'bar',
'baz'=>'boom',
'cow'=>'milk',
'php'=>'hypertext processor');
echo arrayDisplay($arr);
Displays:
foo => 'bar', baz => 'boom', cow => 'milk', php => 'hypertext processor'
There are different ways to do this some of them has given.
implode(), join(), var_export(), print_r(), serialize(), json_encode()exc... You can also write your own function without these:
A For() loop is very useful. You can add your array's value to another variable like this:
<?php
$dizi=array('mother','father','child'); //This is array
$sayi=count($dizi);
for ($i=0; $i<$sayi; $i++) {
$dizin.=("'$dizi[$i]',"); //Now it is string...
}
echo substr($dizin,0,-1); //Write it like string :D
?>
In this code we added $dizi's values and comma to $dizin:
$dizin.=("'$dizi[$i]',");
Now
$dizin = 'mother', 'father', 'child',
It's a string, but it has an extra comma :)
And then we deleted the last comma, substr($dizin, 0, -1);
Output:
'mother','father','child'

PHP - Using explode() function to assign values to an associative array

I'd like to explode a string, but have the resulting array have specific strings as keys rather than integers:
ie. if I had a string "Joe Bloggs", Id' like to explode it so that I had an associative array like:
$arr['first_name'] = "Joe";
$arr['last_name'] = "Bloggs";
at the moment, I can do:
$str = "Joe Bloggs";
$arr['first_name'] = explode(" ", $str)[0];
$arr['last_name'] = explode(" ", $str)[1];
which is inefficient, because I have to call explode twice.
Or I can do:
$str = "Joe Bloggs";
$arr = explode(" ", $str);
$arr['first_name'] = $arr[0];
$arr['last_name'] = $arr[1];
but I wonder if there is any more direct method.
Many thanks.
I would use array_combine like so:
$fields = array ( 'first_name', 'last_name' );
$arr = array_combine ( $fields, explode ( " ", $str ) );
EDIT: I would also pick this over using list() since it allows you to add fields should you require without making the list() call unnecessarily long.
You can make use of list PHP Manual (Demo):
$str = "Joe Bloggs";
list($arr['first_name'], $arr['last_name']) = explode(" ", $str);
$arr then is:
Array
(
[last_name] => Bloggs
[first_name] => Joe
)
You cannot do explode(" ", $str)[0] in PHP <= 5.3.
However, you can do this:
list($arr['first_name'], $arr['last_name']) = explode(" ", $str);

Search and replace multiple values with multiple/different values in PHP5?

Is there an inbuilt PHP function to replace multiple values inside a string with an array that dictates exactly what is replaced with what?
For example:
$searchreplace_array = Array('blah' => 'bleh', 'blarh' => 'blerh');
$string = 'blah blarh bleh bleh blarh';
And the resulting would be: 'bleh blerh bleh bleh blerh'.
You are looking for str_replace().
$string = 'blah blarh bleh bleh blarh';
$result = str_replace(
array('blah', 'blarh'),
array('bleh', 'blerh'),
$string
);
// Additional tip:
And if you are stuck with an associative array like in your example, you can split it up like that:
$searchReplaceArray = array(
'blah' => 'bleh',
'blarh' => 'blerh'
);
$result = str_replace(
array_keys($searchReplaceArray),
array_values($searchReplaceArray),
$string
);
$string = 'blah blarh bleh bleh blarh';
$trans = array("blah" => "blerh", "bleh" => "blerh");
$result = strtr($string,$trans);
You can check the manual for detailed explanation.
IN CASE some one is looking for replacing same strings with different values ( per occurence ).. Example, to replace all ## by numbers++ OR values from an array-
$split_at = '##';
$string = "AA ## BB ## CC ## DD";
$new_string = '';
// echo $string;
$replace_num = 1;
$replace_arr = ['first' , 'second' , 'third'];
$split_at_cnt = substr_count($string, $split_at);
for ($split=0; $split <= $split_at_cnt; $split++)
{
$new_string .= str_replace('##', ($replace_num++)." : ".$replace_arr[$split], substr( $string, 0, strpos($string, $split_at)+strlen($split_at)));
$string = substr($string, strpos($string, $split_at)+strlen($split_at));
}
echo $new_string;
str_replace() does that.
You can check the manual for more detailed explanation.
For what you've got there, just pass that array into str_replace as both the search and replace (using array_keys on the search parameter if you want to keep the array as-is).

Categories