Massive content replace on php data - php

I would like to perform massive content replace for some data called from mysql db in a php file.
Firstly, I have prepared an replacement array for content replace:-
$replacement_array = array(
"###123###" => "hello",
"###456###" => "great",
"###789###" => "ok"
);
Secondly, I call data from mysql db, the data would look like this:-
$data = "<input type="text" name="field1" value="###123###"><input type="text" name="field2" value="###789###">";
Thirdly, refer to the array, check up if $data contains any matched value in $replacement_array (this is the black box I wish to consult).
Fourthly, after content replacement, the resulting $data would become this:-
$data = "<input type="text" name="field1" value="hello"><input type="text" name="field2" value="ok">";
I guess the above will involve php in_array(), str_replace() and preg_match(), and I guess the flow may be like this:-
1) use explode() function to chop $data into a new $data_array by ###;
2) check values in $data_array is in_array() of $replacement_array;
3) if in_array(), carry out str_replace(); (in the above example there will be 2 times)
4) $data has proceeded 2 times of content replace, and ready to be used.
if the above steps 3) and 4) are carried out step by step, I it will be easy, however, if I wish to do it in 1 time, how shall I handle it?

You can use str_replace with first parameter as search array and second parameter as replace array.
$arr = array("###123###","###456###","###789###");
$arr1 = array("hello","great","ok");
str_replace($arr,$arr1, $data);

Related

PHP get JSON object value from Input array (array-like name)

I have 3 inputs like this:
<input type="text" name="product[1][name]" >
<input type="text" name="product[1][cost]" >
<input type="text" name="product[1][qty]" >
... which goes until n products
<input type="text" name="product[n][name]" >
<input type="text" name="product[n][cost]" >
<input type="text" name="product[n][qty]" >
and based on the input value a JSON string like this:
{"product[1][name]": "Prod1", "product[1][cost]": "100$", "product[1][qty]": "3", "product[2][name]": "Prod2", ... }
how can I retrieve their name and value because neither json_decode function can take their values because of the array-like name
$decodedObject=json_decode($array['data']); // this data contains the json string
echo $decodedObject->product; // does not work
echo $decodedObject->product[1][qty]; // does not work
is there any simple way?
Or the only way is to cut the name like product[, take the inside elements , and the value after the : and so on?
But how can I even take the object from it without letting PHP know that's not an array ?
Firstly I found an alternative. The problem is that this:
$decodedObject=json_decode($array['data']); // will create an object
will not transform it in an array, instead I have used this:
$decodedObject=json_decode($array['data'], true); // will create an array
after that I had checked how many objects exist, and then just add them to another array:
$i=1;
while(isset($decodedObject["product[$i][qty]"])) // while any element exists
{
$newProducs= array();
$newProducs['name'] = $decodedObject["product[$i][name]"];
$newProducs['cost'] = $decodedObject["product[$i][cost]"];
$newProducs['qty'] = $decodedObject["product[$i][qty]"];
array_push($products, $newProducs); // optional: add to the main array (products) the new-created array (newProducs)
$i++; //increment to search another product
}
The problem was that I was not fully creating an array -_-
While this is not the full answer I still hope somebody will find a better solution and not a change.

Preserve array when submitting a form to a JSON file

I have a form that takes in data and writes to a JSON form in PHP.
I needed to submit an array as a numeric input but it keeps giving me a string. Is it possible to enable the form to submit as an array via text input box?
Form example:
<input type="text" name="arraytobepushed[]" placeholder="EG: 1000,2000,3000" />
The output is:
{
"obj": [{
"arraytobepushed": ["1000,2000,3000"]
}]
}
You could turn the text into an array by using explode() So you would have something like this:
<?PHP
$myArray = explode(',', $_POST['arraytobepushed[]']);
?>
The explode() function splits everything separated by the first argument (in this case a comma) you pass and puts it into an array.
So if your inputted was 1000, 2000, 3000 your $myArray would look like:
index 0 = "1000" ($myArray[0])
index 1 = "2000" ($myArray[1])
index 2 = "3000" ($myArray[2])
Keep in mind that the values are still strings, not integers. If you want to make them integers you can do this:
$myArray = array_map('intval', explode(',', $_POST['arraytobepushed[]']));
This makes all your elements into integers like so:
index 0 = 1000 ($myArray[0])
index 1 = 2000 ($myArray[1])
index 2 = 3000 ($myArray[2])
No. Forms submit text.
PHP special cases fields with [] in the name as fields to be expressed in an array. It has no special case feature to treat a field as a number instead of a string. You need to convert the data explicitly.

Insert string between quotation marks using RegEx

I am allowing the user to create XML elements with blank attribute values such as this:
<crimes id="" total="" />
at the same time I am also retrieving an associative array from a database to be used to fill up the attributes that the XML specifies. The array will look like this:
array(
theft => 123,
burglary => 456
)
After retrieving the array, I want to use that array to populate the attribute values of the XML which have been passed in. So as an example, the first array element combined with the example XML would look like this:
<crimes id="theft" total="123" />
Is there a way to use regular expression in PHP to insert the array values between the quotation marks of the XML attributes?
The only time this will work, is if the XML tags you receive are consistent. They need to be the same every time, otherwise there is no pattern, and regex is used for matching patterns.
If your tags will always have id and total, then I can write a regex for it. But if they sometimes have one or the other, it gets too complicated and you need a parser.
Although (as you've been already told) you should better use SimpleXML or DOM for this, here is a custom RegEx solution you asked for:
$list = array(
"theft" => 123,
"burglary" => 456
);
$template = '<crimes id="" total="" />';
foreach($list as $key => $value)
{
$s = preg_replace('/(id=")(")/', '${1}'.$key.'${2}', $template);
$s = preg_replace('/(total=")(")/', '${1}'.$value.'${2}', $s);
echo htmlentities($s)."<br>";
}
Here is its output:
<crimes id="theft" total="123" />
<crimes id="burglary" total="456" />
If "id" or "total" is missing - it just omits it.

How to pass an array using $_POST?

I know there are some similar questions but none of them solves my issue.
I have a simple form:
<form method="post">
Import data: <textarea type="text" name="import"></textarea>
<input type="submit">
</form>
Then I get data from the "import" field:
$current = my_data();
$import = $_POST['import'];
$merge = array_merge($current,$import);
The problem is, even if I paste:
array('foo' => 'bar')
I get:
Warning: array_merge(): Argument #2 is not an array in
(address)
on line (line)
I can't change the HTML markup and I have to paste arrays there. Any ideas how to fix it? I've been reading about serialize() but not sure if there's anything to serialize is array() is not array() for PHP. Why is that? Any solutions? Thanks a lot!
UPDATE
$current hold an array of options for my theme.
$merge is supposed to hold the same keys with different values (around 30-50 of them, not multidimensional but might be in the future), but of course users might add new ones so in order to ignore them I'm actually using:
$imported_options = array_merge($current_options , array_intersect_key($_POST["import"], $current_options ));
(simplified this one as it's just an example)
So after all I want to load an array from the form and update the other array with it.
PHP will not create arrays in $_GET/$_POST unless you tell it to:
Import data: <textarea type="text" name="import[]"></textarea>
^^---- need these
Without the [], PHP will treat any duplicate field names as strings to be overwritten. With [] in the name, PHP will treat them as new elements in an array.
You can do
$current['import'] = $import;
Or you can change your html this way:
<textarea type="text" name="myarray['import']"></textarea>
And in php:
$import = $_POST['myarray'];
The second argument is not an array.
$_POST['import'] = value received from the form.
With that said, try:
$current [] = $_POST['import'];
What are you trying to get from $_POST['import'] ?
you are using a textarea to get an array?
if it's just a single variable then use array_push
http://php.net/manual/es/function.array-push.php
for array_merge you need to have 2 arrays.

how to send array values through url in PHP?

how to send array through url in PHP?
I have an array of product ids i want to use these id through url because this is the osCommerce needs it in which i am working in, how can i do it?
Generally osCommerce asks for the single product insertion which in turn gives me back a product id which i pass into the url and get it in shopping cart where i am shown this added product, but now i have multiple products added in first page with different generated product ids and i have to display these products the same way they are displayed in genaral, for which i will need all these generated ids here in url
Your looking for http_build_query().
Example from php.net:
$data = array('foo'=>'bar',
'baz'=>'boom',
'cow'=>'milk',
'php'=>'hypertext processor');
echo http_build_query($data);
// foo=bar&baz=boom&cow=milk&php=hypertext+processor
echo http_build_query($data, '', '&');
// foo=bar&baz=boom&cow=milk&php=hypertext+processor
?arr[]=abc&arr[]=pqr&arr[]=xyz&arr[]=xxx
well what i would do is json_encode(php json) the array and assign that to a variable in php. you can then urlencode the variable to send it via the url. On the other end you can json_decode. Do look up for json if you are not aware of it. its very powerful and useful though.
You can either serialize() it or send it as ?a[]=1&a[]=val2&someOtherArg=val. This will give a $_GET array like:
array(
'a' => array(
0 => '1',
1 => 'val2',
),
'someOtherArg' => 'val'
)
Do note, however, that you should probably keep your entire query below ~2k characters. (more)
If you are POST-ing data, then name your fields with PHP array-style syntax:
<input type="text" name="myArray[]" value="A">
<input type="text" name="myArray[]" value="B">
<input type="text" name="myArray[]" value="C">
If you want to pass the data in a GET request, you can separate the data and split it server side using explode:
page.php?myData=A,B,C,D
...
$myArray = explode(',', $_POST['myData']);
It should be sufficient to encode them like this:
http://your.url/page.php?myArray[0]=val1&myArray[1]=val2
If you already have the product IDs in an array, then you can use the http_build_query() function, which will encode the array like thus:
http://www.example.com/?pid[]=1&pid[]=2&pid[]=3 ...
Hope that helps.

Categories