Hello I have this variable
$str="101,102,103,104,105,#,106#107"
//or array
$str_arr = array( 0 => '101', 1 => '102', 2 => '103', 3 => '104',
4 => '105', 8 => '#' , 9 => '106# 107');
I want to remove the symbol # between comma
The symbol may be /,\,-,| not comma
The symbol between number is correct, so it remains (key 9)
I do not know, if I had these cases but I will study it
$str="101,102,103,104,105#, 106" // One of the symbols in the end of number
$str="101,102,103,104,105,#106" // One of the symbols in the the beginning of number
This is The different possibilities
$str="101,102,103,/,104|,#105,106#107" //replace all symbol in the beginning and the end of number not betwwen number
this is result
$str="101,102,103,104,105,106#107";
Thanks
Convert the string to array using explode by ,. Parse the array using foreach loop. trim() the # or any set of characters like #-|\/ from the beginning and end of every string, then check for empty values and push non empty values to the $arr array. Then you can join the array into a string using implode. You can do it like this:
$arr = array();
$str="101,102,103,104,105,#,106#107";
$str = explode(',', $str);
foreach($str as $s){
$s = trim($s, "#-|\/");
if(!empty($s)){
$arr[] = $s;
}
}
$final_str = implode(',', $arr);
var_dump($final_str);
I have a string like this:
'The Pear and Orange are tasty. Which one do you prefer? Pear or Orange?'
I need to replace the 'Pear' and 'Orange' strings at the end and wrap them in links. I have the following information in JSON format:
"string": "The Pear and Orange are tasty. Which one do you prefer? Pear or Orange?",
"links": {
"55": [
{
"url": "http://example.com/pear",
"name": "Pear",
"offset": 55,
"length": 4
}
],
"63": [
{
"url": "http://example.com/orange",
"name": "Orange",
"offset": 63,
"length": 6
}
]
I want to use the offset and length to replace the strings rather than relying on the names, because the main string may contain multiple occurrences of the words.
What I've tried:
1) I've tried using a foreach loop to loop through the links in the JSON and replace them using substr_replace but after the first loop the offset is then not accurate as I've replaced the first string with a link, which increases the length of the original string by 20-30 characters.
2) I then tried passing replace, offset and length arrays to substr_replace to try to replace all the strings in one go, but that didn't work as the original string isn't in an array format, it's just a plain string.
Does anyone have any ideas or pointers for me? Any help would be hugely appreciated as I'm pulling my hair out. It seems so simple yet I can't quite get it!
Many thanks,
John
Your first instinct was right. The only change you need to make is to make the for loop start with the last entry and loop backward, in stead of the other way around. This will work because the offset of a word only changes if you change something that comes before that word in the string.
for($i = count($links)-1; $i >= 0; $i--) {
str_replace( ... );
}
The above approach requires that the links are sorted according to their offset, however, with the highest offset coming last in the array. If the links aren't sorted, you will have to do that first. But if you need to sort the array, you might as well sort them so that the highest offset comes first and loop through the array the normal way around.
For example:
$links = array(
array( 'name' => 'Pear', 'offset' => 55 ),
array( 'name' => 'Orange', 'offset' => 63 ),
array( 'name' => 'LAST', 'offset' => 0 ),
array( 'name' => 'MIDDLE', 'offset' => 60 ),
array( 'name' => 'FIRST', 'offset' => 1000)
);
function mySort($a, $b) {
return $b['offset'] - $a['offset']; // Sorts elements with higher offset first
}
usort($links, 'mySort');
This question already has answers here:
Populate array of integers from a comma-separated string of numbers and hyphenated number ranges
(8 answers)
Closed 6 months ago.
I have a text box that a user can paste a string of comma separated numbers and it puts that into an array. However, in some cases that string may contain numbers separated by a dash and I need to fill in the missing numbers where that dash appears.
Example:
1, 4, 7, 20-25, 31, 46, 100
Needs to become:
1, 4, 7, 20, 21, 22, 23, 24, 25, 31, 46, 100
How might I go about doing this? The gap wont always be 5 numbers and there could be more than one set of dashed numbers in the string that is input.
Here is one way, without a regex:
It is:
Parsing the input string with str_getcsv() to separate it into its individual elements, then trimming whitespace around each element with trim() and array_map().
Iterating over each element, searching for a dash. If it finds a dash, it found a range of numbers, so it separates them into the start and end indexes by explode()ing on the dash, and forms the correct range between $start and $end with range(). It then merges that newly formed range with what has already been formed as the result using array_merge().
If, during iteration, it didn't find a dash, it assumes you have a literal number, and adds just that number to the resulting array.
That's it!
$input = '1, 4, 7, 20-25, 31, 46, 100';
$entries = array_map( 'trim', str_getcsv( $input));
$result = array();
foreach( $entries as $entry) {
if( strpos( $entry, '-') !== false) {
list( $start, $end) = explode( '-', $entry);
$result = array_merge( $result, range( trim($start), trim($end)));
} else {
$result[] = $entry;
}
}
You can see from this demo that it produces:
Array (
[0] => 1
[1] => 4
[2] => 7
[3] => 20
[4] => 21
[5] => 22
[6] => 23
[7] => 24
[8] => 25
[9] => 31
[10] => 46
[11] => 100 )
Edit: To form the resulting string, instead of the array, you just need a call to implode(), like so:
echo implode( ', ', $result);
This will produce:
1, 4, 7, 20, 21, 22, 23, 24, 25, 31, 46, 100
$data = '1, 4, 7, 20-25, 31, 46, 100';
$elts = explode(',', $data);
$res = array();
foreach ($elts as $elt) {
$elt = trim($elt);
if (preg_match('/(\d+)-(\d+)/', $elt, $matches) === 1) {
$res = array_merge($res, range($matches[1], $matches[2]));
} else {
$res[] = intval($elt);
}
}
var_dump($res);
My solution :DEMO HERE
First delete spaces using str_replace()
explode() string using , to array of integers.
explode() every element using - to check if it's a range or just a single integer.
if it's a range , loop using for() or range() and add $i to $newArray , else add the element to $newArray.
implode() using , and print the result.
PHP code :
<?php
$str=str_replace(' ', '', '1, 4, 7, 20-25, 31, 46, 100');
$arr = explode(',',$str);
foreach($arr as $elem){
$values=explode('-',$elem);
if(count($values)!=1) for($i=$values[0];$i<=$values[1];$i++) $newArr[]=$i;
else $newArr[]=$elem;
}
echo implode(',',$newArr);
?>
OUTPUT:
1,4,7,20,21,22,23,24,25,31,46,100
Simple code :
split string by delimiter , with explode();
remove space from the beginning and end of a string with trim;
function array_map is used so you don't need to do foreach loop just to apply trim() to every element;
create empty array where you will store new elements;
iterate over each number or range with foreach;
do points 1., 2. and 3. again on every iteration;
split string by delimiter - with explode() even if string doesn't have delimiter - in it; result will be array with one or multi elements;
if point 6. has array with multiple elements, that means that there is range involved, so use function range() to create an array containing a range of elements;
store new numbers to point 4. array with array_merge() function;
when point 4. array is full generated; sort values with sort(), so you don't have output like 5, 3, 1, 4 etc. (delete this function if you don't need this functionality);
remove duplicates with array_unique(), so you don't have output like 4, 4, 4, 4, 5 etc. (delete this function if you don't need this functionality)
to convert array back to string like you inputed, use implode() function.
|
function fillGaps($s) {
$s = array_map('trim', explode(',', $s));
$ss = [];
foreach ($s as $n) {
$n = array_map('trim', explode('-', $n));
if (count($n) > 1) $n = range($n[0], end($n));
$ss = array_merge($ss, $n);
}
sort($ss); # remove if you don't need sorting
$ss = array_unique($ss); # remove if duplicates are allowed
return implode(', ', $ss);
}
Example :
Your example :
echo fillGaps('1, 4, 7, 20 - 25, 31, 46, 100');
# 1, 4, 7, 20, 21, 22, 23, 24, 25, 31, 46, 100
This code will also work for multiple gaps, like :
echo fillGaps('100-105-110');
# 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110
You can even go reverse :
echo fillGaps('10-5');
# 5, 6, 7, 8, 9, 10
# or remove function sort() and output will be 10, 9, 8, 7, 6, 5
Remove duplicates :
echo fillGaps('2-4, 4, 4, 5');
# 2, 3, 4, 5
This can be done without the using a regular expression.
Get the user input, explode with , as the delimiter, and you'll get an array of all numbers.
Now use an if statement to check if the string contains a dash.
If it does, explode it again with the delimiter -. Now you'll get two numbers
Use range() to create an array of numbers within that range
Use implode() to join them by a comma.
As a useful function:
Code:
function fill_string_gaps($input)
{
$parts = explode(',', $input);
$resultArray = array();
foreach ($parts as $part) {
if(strpos(trim($part), '-')) {
list($num1, $num2) = explode('-', $part);
$expanded_num_array = range($num1, $num2);
$resultArray = array_merge($resultArray, $expanded_num_array);
} else {
$resultArray[] = trim($part);
}
}
$comma_separated = implode(', ', $resultArray);
return $comma_separated;
}
Usage:
$input = '1, 4, 7, 20-25, 31, 46, 100';
echo fill_string_gaps($input;)
Test cases:
echo fill_string_gaps('1-5');
echo fill_string_gaps('1-5, 12, 24');
echo fill_string_gaps('2, 2, 4, 5-8');
Output:
1, 2, 3, 4, 5
1, 2, 3, 4, 5, 12, 24
2, 2, 4, 5, 6, 7, 8
See it in action!
I need to parse a string of alternating letters and number and populate an array where the letters are the keys and the numbers are the values.
Example:
p10s2z1234
Output
Array(
'p' => 10,
's' => 2,
'z' => 1234
)
Use regex to get desired values and then combine arrays to get associative array. For example:
$str = 'p10s2z1234';
preg_match_all('/([a-z]+)(\d+)/', $str, $matches); //handles only lower case chars. feel free to extend regex
print_r(array_combine($matches[1], $matches[2]));
Scenario 1: You want to parse the string which has single letters to be keys, will produce three pairs of values, and you want the digits to be cast as integers. Then the best, most direct approach is sscanf() with array destructuring -- a single function call does it all. (Demo)
$str = 'p10s2z1234';
[
$k1,
$result[$k1],
$k2,
$result[$k2],
$k3,
$result[$k3]
] = sscanf($str, '%1s%d%1s%d%1s%d');
var_export($result);
Output:
array (
'p' => 10,
's' => 2,
'z' => 1234,
)
Scenario 2: You want the same parsing and output as scenario 1, but the substrings to be keys have variable/unknown length. (Demo)
$str = 'pie10sky2zebra1234';
[
$k1,
$result[$k1],
$k2,
$result[$k2],
$k3,
$result[$k3]
] = sscanf($str, '%[^0-9]%d%[^0-9]%d%[^0-9]%d');
var_export($result);
Scenario 3: You want to parse the string with regex and don't care that the values are "string" data-typed. (Demo)
$str = 'pie10sky2zebra1234';
[
$k1,
$result[$k1],
$k2,
$result[$k2],
$k3,
$result[$k3]
] = preg_split('/(\d+)/', $str, 0, PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE);
var_export($result);
Scenario 4: If you don't know how many pairs will be generated by the input string, use array_combine(). (Demo)
$str = 'pie10sky2zebra1234extra999';
var_export(
preg_match_all('/(\D+)(\d+)/', $str, $m)
? array_combine($m[1], $m[2])
: []
);
I have string that look like Array that fetched from other webservice like this
[
[
[189, 'Brazil Serie A', 0, ''],
[
[1053230, 'Flamengo', 'Atletico Goianiense', '1.196', 10, '07/02/2012 04:30', 0, 9, 1, 0, '', 0]
],
[0, [
[10770901, 0, 5000.00],
[1, 17988654, '-0.78', '0.70', '1.0', 1],
[3, 17965783, '0.97', '0.93', '2.5-3'],
[7, 17965787, '-0.89', '0.77', '0.50', 1],
[9, 17965789, '0.70', '-0.82', '1.0']
]]
],
[, , [0, [
[10748028, 0, 3000.00],
[1, 17965781, '0.85', '-0.93', '0.5-1', 1],
[3, 17988655, '0.79', '-0.89', '2.50']
]]]
]
Is it possible to parsing to PHP Array or convert to JSON ?
As ctrahey noted, the single quotes need to be swapped to double quotes to be valid JSON. The commas without anything preceding them also have to go.
// quote to double quote
$input = str_replace("'", '"', $input);
// remove empty commas
$input = preg_replace('/,\s*,/', ',', $input);
$input = preg_replace('/\[\s*,/', '[', $input);
$output = json_decode($input));
I've tried to keep it simple and build a little flexibility in.
Um, at first glance... if you convert your single quotes to double quotes, you already have JSON. I switched about half and it was validating okay through that point.
See the spec for details, but this is essentially just a bunch of arrays. The double-quote requirement for strings is clearly stated there, and the rest looks okay.