how to replace space of a string with "," and convert into array - php

I have a text box.
I am enter the value in text box like 12 13 14.
and i am want to convert this into 12,13,14 and then convert it into array and show each separate value.

If your form field asks for the values without a comma, then you will need to explode the POST data by space. What you're doing now is imploding it by comma (you can't implode a string to begin with), and then trying to pass that into a foreach loop. However, a foreach loop will only accept an array.
$ar = explode(' ',$da);
That simple change should fix it for you. You will want to get rid of the peculiar die() after your foreach (invalid syntax, and unclear what you're trying to do there!), and validate your data before the loop instead. By default, if you explode a string and no matching delimiters are found, the result will be an array with a single key, which you can pass into a loop without a problem.

Are you sure you want to expect the user enters data in that particular format? I mean, what if the user uses more than one space character, or separate the numbers actually with commas? or with semicolons? or enters letters instead of numbers? Anyway.. at least you could transform all the spaces to a single space character and then do the explode() as suggested:
$da = trim(preg_replace('/\s+/', ' ', $_POST['imp']));
$ar = explode(' ', $da);
before your foreach().

use explode instead of implode as
The explode() function breaks a string into an array.
The implode() function returns a string from the elements of an array.
and you cannot do foreach operation for a string.
$da=$_POST['imp'];
$ar = explode(' ',$da);
foreach($ar as $k)
{
$q="insert into pb_100_fp (draw_3_fp) values ('".mysqli_real_escape_string($conn, $k)."')";
$rs=mysqli_query($conn, $q);
echo $k.",";
}
then you will get this output
o/p : 12,13,14,

Related

PHP - preg_replace how to add an extra "]" and an extra "["

Is there any way to do this with preg_replace or other php code?
I have a string that looks like this:
[[10],[11],[2],[3],[5],[1],[10],[15],[20],[21],[14],[16],[17],[6],[9],[4]]
I want to display like this:
[[10,11],[2,3],[5,1],[10,15],[20,21],[14,16],[17,6],[9,4]]
So I replaced the "],[" part with str_replace
$xy1 = str_replace('],[', ',', $xy1);
And now looks like this:
[[10,11,2,3,5,1,10,15,20,21,14,16,17,6,9,4]]
But I need to add an extra "]" after every second number and an extra [ after every second comma ex.:
[[10,11],[2,3],[5,1]
A couple of possibilities:
The string is valid JSON, whether it was intended to be or not, so you can decode it, chunk the resulting array and re-encode it.
$result1 = json_encode(array_chunk(array_column(json_decode($string),0),2));
If you are producing the string in your previous code via json_encode it would be much better to just use array_chunk at that time, but if it's coming from some other source you obviously can't do that.
For this specific string, it may be less cumbersome to pair the numbers with a regex.
$result2 = preg_replace('/(\d+)\D+(\d+)/', '$1,$2', $string);
Or a combination of both ways, extract all the numbers and then chunk and encode.
preg_match_all('/\d+/', $string, $numbers);
$result3 = json_encode(array_chunk($numbers[0], 2), JSON_NUMERIC_CHECK);
This might help, extract the nested array values and then group them by pairs.
$newArray = array_chunk( array_column( $array, 0 ), 2 );

How to fix white space error in array_count_value

i am making php array count value function i am taking values from file get content and using it in it and want to count values but due to space its not working properly Here is my codes
$data = file_get_contents('testr.txt');
preg_match_all('#mob:-(\S+)-#',$data,$matches);
$nu=$matches[1];
$n=implode($nu,',');
$n="9024453561,9024453561,9024453561,9024453561,9024453561 ";
//in value of $n i am getting spce at end so array_count _value not working
$array = array($n);
$counts = array_count_values($array);
echo $counts['9024453561'];
Using array_map(), map over your data where your call implode like so:
$n=array_map('trim', implode($nu,','));
This will remove any white space you have in your array values.
Hope that helps,
You do not split the string into an array by array($n). Instead you get a single element containing the entire string including commas. Use trim and preg_split to get an array of values.
$n="9024453561,9024453561,9024453561,9024453561,9024453561 ";
$array = preg_split('~\\s*,\\s*~u', trim($n));
$counts = array_count_values($array);
echo $counts['9024453561'];
This also splits a string like " 123 , 456 , 789 ". \s* means zero or more whitespaces. The double slash is to escape the slash in the string literal. trim removes spaces from the begin and the end of the entire string.
There is no need to go through the implode at all, just call array_count_values on your preg_match_all result:
$data = file_get_contents('testr.txt');
preg_match_all('#mob:-(\S+)-#',$data,$matches);
$nu=$matches[1];
$counts = array_count_values($nu);
echo $counts['9024453561'];

Imploding $_POST values with comma

I have a textarea in my form where user will enter data line by line. I am processing it using $_POST . I have to separate each line by a comma while echoing it in php
the text area content like this
233
123
abf
4c2
I tried with below code
$array = array($_POST['devices']);
$device = implode(",", $array);
echo $device;
But it not showing commas between each value, rather I will get plain values like
233 123 abf 4c2
How can I show it like
233,123,abf,4c2
All above values are part of the text area,
You can not split a string into an array simply by creating an array().
You need to convert it to an array by splitting the lines:
$devices = preg_split('/\s+/', $_POST['devices']);
echo implode(',', $devices');
Note: You may want to split strictly on line endings. But the above will get you started.
No need to summon the power of regular expressions. You can simply implode the results of an explode.
$str = implode(",", explode("\n", $_POST['devices']));

PHP remove number from comma seperated string stored in db [duplicate]

This question already has answers here:
Fastest way of deleting a value in a comma separated list
(4 answers)
Closed 2 years ago.
I am storing numbers in a database with a string like 5,55,15,17,2,35
I want to remove say number 5 from the string, keeping the comma seperation set like it is.
The problem with using str_replace() is that all of the 5's will be removed. If i use str_replace('5,'', $string) thats fine, but the comma wouldn't be after the 5 if it was in the middle of the string or at the end. That same str_replace would also remove part of 15, and 55,
Am i missing something?
$array = explode(',', $string);
foreach ($array as $k => $v)
if ($v == 5) unset($array[$k]);
$string = implode(',', $array);
You probably shouldn't be storing a comma separated list of values in a single database column in the first place. It looks like a one-to-many association, which should be modeled with a separate table.
Split the string first by comma so you can work with the numbers directly. Remove 5 from the array, then recombine the array into a comma-delimited string.
Here's an example:
<?php
$input = '5,55,15,17,2,35';
echo "Input: $input<br />";
// Split the string by "exploding" the string on the delimiter character
$nums = explode(',', $input);
// Remove items by comparing to an array containing unwanted elements
$nums = array_diff($nums, array(5));
// Combine the array back into a comma-delimited string
$output = implode(',', $nums);
echo "Output: $output<br />";
// Outputs:
// Input: 5,55,15,17,2,35
// Output: 55,15,17,2,35
?>
str_replace([$num.",",",".$num],"",$input);
U can try something like this:
// Convert string into array of numbers
$arrOfNumbers = explode(',', $string);
// Find id of number for del
$numberForDelId = array_search($numberForDel, $arrOfNumbers);
//Delete number
unset($arrOfNumbers[$numberForDelId]);
// Convert back to string
$resultString = implode(',' $arrOfNumbers)
You should:
get the string
then "explode" the values into an array
and re-create the string without the number you want to remove.

Get first part of string in php

I've got a string of:
test1.doc,application/msword,/tmp/phpDcvNQ5,0,23552
I want the first part before the comma. How do I get the first part 'test1.doc' on it's own without the rest of the string?
The string came from an array I imploded:
$uploadFlag=implode( ',', $uploadFlag );
echo $uploadFlag;
If it's easier to extract just the first value off the array on it's own that would also do the job. I don't think the array has any keys.
Thanks in advance.
echo $uploadFlag[0];
Uh, try that in place of that whole chunk of code. Since you're imploding it, you could just grab the first piece instead. That ought to echo the proper value!
$parts = explode(',', $uploadFlag);
$firstPart = $parts[0];
Use this code:
$part = substr($uploadFlag , 0, strpos($uploadFlag , ','));
To extract it from the string, you can use preg_replace() for example.
$firstPart = preg_replace('/,.*$/', '', $uploadFlag);
In the above example, the regular expression replaces everything (.*) that follows the first comma (,) until the end of the string ($) with nothing ('').
Or, if you can use the $uploadFlag array before replacing it with the imploded string, then you can use reset() to go to the first element in the array and current() to extract its value.
reset($uploadFlag);
$firstPart = current($uploadFlag);
Implode is not the right function. It takes an array and combines into one string. You are trying to do the reverse operation, which is handled by explode:
$uploadFlag=explode( ',', $uploadFlag );
echo $uploadFlag;
echo array_shift(array_slice($uploadFlag, 0, 1)); will output the first element of your array beit an associative or numbered array.

Categories