How to fix white space error in array_count_value - php

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'];

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 replace space of a string with "," and convert into array

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,

Remove text between last 2 slashes (PHP)

I have made a system with browsing files; Now I have a problem:
My path string like this: A/Abba/2004/
I want to remove the text between the last 2 slashes (which is 2004 in this case).
So the output should look like A/Abba/
Can anyone help me as how to archive this in php?
Thanks.
If you try to remove last part of string you can do this this way:
$input = 'A/Abba/2014/';
$array = array_filter(explode('/', $input));
array_pop($array);
$correct = implode('/', $array);
array_filter removes empty strings from array
explode converts string to array by given delimiter
array_pop remove last item from given array
implode converts array to string using given 'glue'

TextArea to Array with PHP

I'm trying to figure out how to convert html textarea into php array,
I've used a form with POST to deliver the query to the php script,
and the php file is getting them with the following line:
$ids = array($_POST['ids']);
Needless to say that it puts everything into one line
Array ( [0] => line1 line2 line3 line4 )
I need the final results to replace this:
$numbers = array(
"line1",
"line2",
"line3",
"line4"
);
What would be the best approach to divide and re-parse it ?
Using an explode on \n is a proper way to get new lines. keep in mind though that on some platforms the end of line is actually send by \r\n, so just exploding on \n could leave you with extra data on the end of each line.
My suggestion would be to remove the \r before exploding, so you dont have to loop through the entire array to trim the result. As a last improvement, you dont know that there actually is a $_POST['ids'], so always check it first.
<?
$input = isset($_POST['ids'])?$_POST['ids']:"";
//I dont check for empty() incase your app allows a 0 as ID.
if (strlen($input)==0) {
echo 'no input';
exit;
}
$ids = explode("\n", str_replace("\r", "", $input));
?>
I would've done the explode by Hugo like this:
$ids = explode(PHP_EOL, $input);
manual Predefined Constants
Just my two cents...
Use this
$new_array = array_values(array_filter(explode(PHP_EOL, $input)));
explode -> convert textarea to php array (that lines split by new line)
array_filter -> remove empty lines from array
array_values -> reset keys of array
If the textarea simply has line breaks per entry then I'd do something like:
$ids = nl2br($_POST['ids');
$ids = explode('<br />',$ids); //or just '<br>' depending on what nl2br uses.
Try with explode function:
$ids = $_POST['ids']; // not array($_POST['ids'])
$ids = explode(" ", $ids);
The first parameter is the delimiter which could be space, new line character \r\n, comma, colon etc. according to your string from the textarea (it's not clear from the question whether values are separated by spaces or by new lines).

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