How to truncate a delimited string in PHP? - php

I have a string of delimited numerical values just like this:
5|2288|502|4208|55|23217|235|10|3845|19053|1885|61|324|9004| ...etc.
Depending on the circumstance, the string may have only 1 value, 15 values, all the way up to 100s of values, all pipe delimited.
I need to count off (and keep/echo) the first 10 values and truncate everything else after that.
I've been looking at all the PHP string functions, but have been unsuccessful in finding a method to handle this directly.

Use explode() to separate the elements into an array, then you can slice off the first 10, and implode() them to create the new string.
$arr = "5|2288|502|4208|55|23217|235|10|3845|19053|1885|61|324|9004";
$a = explode ('|',$arr);
$b = array_slice($a,0,10);
$c = implode('|', $b);

Use PHP Explode function
$arr = explode("|",$str);
It will break complete string into an array.
EG: arr[0] = 5, arr[1] = 2288 .....

I would use explode to separate the string into an array then echo the first ten results like this
$string = "5|2288|502|4208|55|23217|235|10|3845|19053|1885|61|324|9004";
$arr = explode("|", $string);
for($i = 0; $i < 10; $i++){
echo $arr[$i];
}

Please try below code
$str = '5|2288|502|4208|55|23217|235|10|3845|19053|1885|61|324';
$arrayString = explode('|', $str);
$cnt = 0;
$finalVar = '';
foreach ($arrayString as $data) {
if ($cnt > 10) {
break;
}
$finalVar .= $data . '|';
$cnt++;
}
$finalVar = rtrim($finalVar, '|');
echo $finalVar;

Related

PHP remove values below a given value in a "|"-separated string

I have this value:
$numbers= "|800027|800036|800079|800097|800134|800215|800317|800341|800389"
And I want to remove the values below 800130 including the starting "|". I guess it is possible, but I can not find any examples anywhere. If anyone can point me to the right direction I would be thankful.
You could split the input string on pipe, then remove all array elements which, when cast to numbers, are less than 800130. Then, recombine to a pipe delimited string.
$input= "|800027|800036|800079|800097|800134|800215|800317|800341|800389";
$input = ltrim($input, '|');
$numbers = explode("|", $input);
$array = [];
foreach ($numbers as $number) {
if ($number >= 800130) array_push($array, $number);
}
$output = implode("|", $array);
echo "|" . $output;
This prints:
|800134|800215|800317|800341|800389
This should work as well:
$numbers= "|800027|800036|800079|800097|800134|800215|800317|800341|800389";
function my_filter($value) {
return ($value >= "800130");
}
$x = explode("|", $numbers); // Convert to array
$y = array_filter($x, "my_filter"); // Filter out elements
$z = implode("|", $y); // Convert to string again
echo $z;
Note that it's not necessary to have different variables (x,y,z). It's just there to make it a little bit easier to follow the code :)
PHP has a built in function preg_replace_callback which takes a regular expression - in your case \|(\d+) - and applies a callback function to the matched values. Which means you can do this with a simple comparison of each matched value...
$numbers= "|800027|800036|800079|800097|800134|800215|800317|800341|800389";
echo preg_replace_callback("/\|(\d+)/", function($match){
return $match[1] < 800130 ? "" : $match[0];
}, $numbers);
Use explode and implode functions and delete the values that are less than 80031:
$numbers= "|800027|800036|800079|800097|800134|800215|800317|800341|800389";
$values = explode("|", $numbers);
for ($i=1;$i<sizeof($values);$i++) {
if (intval($values[$i])<800130) {
unset($values[$i]);
}
}
// Notice I didn't start the $i index from 0 in the for loop above because the string is starting with "|", the first index value for explode is ""
// If you will not do this, you will get "|" in the end in the resulting string, instead of start.
$result = implode("|", $values);
echo $result;
It will print:
|800134|800215|800317|800341|800389
You can split them with a regex and then filter the array.
$numbers= "|800027|800036|800079|800097|800134|800215|800317|800341|800389";
$below = '|'.join('|', array_filter(preg_split('/\|/', $numbers, -1, PREG_SPLIT_NO_EMPTY), fn($n) => $n < 800130));
|800027|800036|800079|800097

Want to iterate a string that after each charater there will be a space in PHP

I want to iterate a string in the manner that after each character there should be a space and there will be new string(word) as per the main string character count.
For example
If I put the string "v40eb" as an input. Then Output be something like below.
v 40eb
v4 0eb
v40 eb
v40e b
OR
In Array form like below.
[0]=>v 40eb[1]=>v4 0eb[2]=>v40 eb[3]=>v40e b
I am using PHP.
Thanks
Well, you can divide the process of putting a space into 2 parts.
Get first part of the substring, append a space.
Get second part of the substring and join them together.
Use substr() to get a substring of a string.
Snippet:
<?php
$str = "v40eb";
$result = [];
$len = strlen($str);
for($i=0;$i<$len;++$i){
$part1 = substr($str,0,$i+1);
if($i < $len-1) $part1 .= " ";
$part2 = substr($str,$i+1);
$result[] = $part1 . $part2;
}
print_r($result);
Demo: https://3v4l.org/XGN0a
You could simply loop over the char positions and use substr to get the two parts for each:
$input = 'v40eb';
$combinations = [];
for ($charPos = 1, $charPosMax = strlen($input); $charPos < $charPosMax; $charPos++) {
$combinations[] = substr($input, 0, $charPos) . ' ' . substr($input, $charPos);
}
print_r($combinations);
Demo: https://3v4l.org/EeT1V
$input = 'v40eb';
for($i = 1; $i< strlen($input); $i++) {
$array = str_split($input);
array_splice($array, $i, 0, ' ');
$output[] = implode($array);
}
print_r($output);
Dont forget to check the codec. You might use mb_-prefix to use the multibyte-functions.

Mix array with ancestor elements

Seems to be very simple but I'm like, losing a lot of time on this... and no success...
If I have a string:
$str = "She sells seashells"
So I turn every word into an array element
$array = explode(" ", $str);
What I need is, every word receive the ancestor element (if any) and the next ones...
Example result in json format (more easy to show)
"{"She":["sells","seashells"],"sells":["She","seashells"],"seashells":["She","sells"]}"
Can somebody help?
Thanks!
Really, you can copy a source array for each key, excluding that key:
$str = "She sells seashells";
$array = explode(" ", $str);
$res = [];
for($i = 0; $i < count($array); $i++) {
$res[$array[$i]] = $array;
unset($res[$array[$i]][$i]);
}
print_r($res);
demo
<?php
$str = "She sells seashells";
$arr = explode(" ",$str);
$length = count($arr);
$result = [];
for($i = 0;$i < $length;++$i){
$result[$arr[$i]] = [];
foreach ($arr as $each_val) {
if($each_val === $arr[$i]) continue;
$result[$arr[$i]][] = $each_val;
}
}
echo json_encode($result);
OUTPUT:
{"She":["sells","seashells"],"sells":["She","seashells"],"seashells":["She","sells"]}
Explode the string based on spaces.
Have a result array and make the current iteration value in for loop as the key for it.
Loop again over the array and check if current value matches with outer for loop value. If yes, then continue, else add that value in this result array key.
In the end, json_encode() it and you are done.

php basic operations question

I have a array of say 50 elements. This array can be of size anything.
I want to have the first 10 elements of the array in a string.
I have the program as:
$array1= array("itself", "aith","Inside","Engineer","cooool","that","it","because");
$i=0;
for($f=0; $f < sizeof(array1); $f++)
{
$temparry = $temparry.array1[$f];
if(($f%10) == 0 && ($f !== 0))
{
$temparray[$i] = $temparray;
$i++;
}
}
==
so that at the end:
I get
temparray1= first 10 elements
temparray2 - next 10 elemnts...
I am not what I am missing in my loops.
After reading your comment, I think you want array_chunk [docs]:
$chunks = array_chunk($array1, 10);
This will create a multidimensional array with each element being an array containing 10 elements.
If you still want to join them to a string, you can use array_map [docs] and implode [docs]:
$strings = array_map('implode', $chunks);
This gives you an array of strings, where each element is the concatenation of a chunk.
This is something you can easily do with array_splice and implode.
Example:
<?php
$array = range(1, 50);
while ( $extracted = array_splice($array, 0, 10) )
{
// You could also assign this to a variable instead of outputting it.
echo implode(' ', $extracted);
}
all you are doing here is creating a temporary value and then deleting it. To save it into a string:
$myArray = array("itself", "aith","Inside","Engineer",
"cooool","that","it","because");
$myString = '';
for($i = 0; $i < 10; $i++) {
$myString .= $myArray[$i];
}
You could also run that inside of another for loop that would run through the entire array giving you ten-element increments.
Actually you can use arrray_slice and implode functions like this:
// put first 10 elements into array output
$output = array_slice($myArray, 10);
// implode the 10 elements into a string
$str = implode("", $output);
OP's fixed code as per comments below:
$array1= array("itself","aith","Inside","Engineer","cooool","that","it","because");
$temparry='';
$temparray = array();
for($f=0; $f < count($array1); $f++)
{
$temparry = $temparry.$array1[$f];
if(($f%3) == 0 && ($f !== 0))
{
$temparray[] = $temparry;
$temparry = '';
}
}
print_r($temparray);

Take a part of a string (PHP)

We are trying to get certain parts of a String.
We have the string:
location:32:DaD+LoC:102AD:Ammount:294
And we would like to put the information in different strings. For example $location=32 and $Dad+Loc=102AD
The values vary per string but it will always have this construction:
location:{number}:DaD+LoC:{code}:Ammount:{number}
So... how do we get those values?
That would produce what you want, but for example $dad+Loc is an invalid variable name in PHP so it wont work the way you want it, better work with an array or an stdClass Object instead of single variables.
$string = "location:32:DaD+LoC:102AD:Ammount:294";
$stringParts = explode(":",$string);
$variableHolder = array();
for($i = 0;$i <= count($stringParts);$i = $i+2){
${$stringParts[$i]} = $stringParts[$i+1];
}
var_dump($location,$DaD+LoC,$Ammount);
Easy fast forward approach:
$string = "location:32:DaD+LoC:102AD:Ammount:294";
$arr = explode(":",$string);
$location= $arr[1];
$DaD_LoC= $arr[3];
$Ammount= $arr[5];
$StringArray = explode ( ":" , $string)
By using preg_split and mapping the resulting array into an associative one.
Like this:
$str = 'location:32:DaD+LoC:102AD:Ammount:294';
$list = preg_split('/:/', $str);
$result = array();
for ($i = 0; $i < sizeof($list); $i = $i+2) {
$result[$array[$i]] = $array[$i+1];
};
print_r($result);
it seems nobody can do it properly
$string = "location:32:DaD+LoC:102AD:Ammount:294";
list(,$location,, $dadloc,,$amount) = explode(':', $string);
the php function split is deprecated so instead of this it is recommended to use preg_split or explode.
very useful in this case is the function list():
list($location, $Dad_Loc, $ammount) = explode(':', $string);
EDIT:
my code has an error:
list(,$location,, $Dad_Loc,, $ammount) = explode(':', $string);

Categories