Get first part of string in php - 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.

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

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,

php - Get string before nth dash (-)

I have a string that looks something like this:
abc-def-ghi-jkl-mno-pqr-stu-vwx-yz I'd like to get the content BEFORE the 4th dash, so effectively, I'd like to get abc-def-ghi-jkl assigned to a new string, then I'd like to get mno assigned to a different string.
How could I go about doing this? I tried using explode but that changed it to an array and I didn't want to do it that way.
Try this:
$n = 4; //nth dash
$str = 'abc-def-ghi-jkl-mno-pqr-stu-vwx-yz';
$pieces = explode('-', $str);
$part1 = implode('-', array_slice($pieces, 0, $n));
$part2 = $pieces[$n];
echo $part1; //abc-def-ghi-jkl
echo $part2; //mno
See demo
http://php.net/manual/en/function.array-slice.php
http://php.net/manual/en/function.explode.php
http://php.net/manual/en/function.implode.php
Can you add your source code? I done this one before but I cant remember the exact source code I used. But I am pretty sure I used explode and you can't avoid using array.
EDIT: Mark M answer is right.
you could try using substr as another possible solution
http://php.net/manual/en/function.substr.php
If I see where you are trying to get with this you could also go onto substr_replace
I guess an alternative to explode would be to find the position of the 4th - in the string and then get a substring from the start of the string up to that character.
You can find the position using a loop with the method explained at find the second occurrence of a char in a string php and then use substr(string,0,pos) to get the substring.
$string = "abc-def-ghi-jkl-mno-pqr-stu-vwx-yz";
$pos = -1;
for($i=0;$i<4;$i++)
$pos = strpos($string, '-', $pos+1);
echo substr($string, 0, $pos);
Code isn't tested but the process is easy to understand. You start at the first character (0), find a - and on the next loop you start at that position +1. The loop repeats it for a set number of times and then you get the substring from the start to that last - you found.

How to get part of a string in php

I have strings like:
t_est1_1
test213_4
tes_tsdfsdf_9
The common part of every string is the LAST underscore _ character.
I need to get the string before this character.
t_est1_12 --> test1
test213_4 --> test213
tes_tsdfsdf_9343 --> testsdfsdf
How can i achieve this in PHP?
Using the basic string functions strpos and substr.
http://fr.php.net/manual/fr/function.explode.php
$a = "abcdef_12345"
$b = array();
// $b[0] = "abcdef";
$b[0] = explode('_',$a,'1');
you can use preg_match function available in php
you need to write regular expression for that...
for example
to get this test1_12 ->> test1
$string='test1_12';
preg_match('((.+?)\_(.*))',$string,$match);
echo $match[1];
What you want is a simple explode, array_slice and implode, also using explode and end, you can get the "id" that is the common part too:
$description = implode('', array_slice(explode('_', $data), 0, -1));
$id = end(explode('_', $data));
As many _ you will have, you'll still be able to expode on them and retrieve the last item containing your id and the first items (0 to -1) will contain your description...

Categories