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 );
Related
I have an array of arrays like:
$array = [["1.","COTV_LITE(1800)"],["2.","COTV_PREMIUM(2200)"]]
Now, I want to implode this array such that it would return something like this:
COTV_LITE(1800)
COTV_PREMIUM(2200)
How do I achieve this? Calling just the implode() function did not work:
implode ('<br>', $array);
You can call array_map() to implode the nested arrays:
echo implode('<br>', array_map(function($a) { return implode(' ', $a); }, $array));
DEMO
output:
1. COTV_LITE(1800)<br>2. COTV_PREMIUM(2200)
You can use variable length arguments variadic in PHP >= 5.6
Option1
$items = [["1.","COTV_LITE(1800)"],["2.","COTV_PREMIUM(2200)"]];
echo implode(' ',array_merge(...$items));
Output
1. COTV_LITE(1800) 2. COTV_PREMIUM(2200)
This is more of a precursor for the next option.
Option2
If you want to get a bit more creative you can use preg_replace too:
$items = [["1.","COTV_LITE(1800)"],["2.","COTV_PREMIUM(2200)"]];
$replace = [
'/^(\d+\.)$/' => '<li>\1 ',
'/^(\w+\(\d+\))$/' => '\1</li>'
];
echo '<ul>'.implode(preg_replace(array_keys($replace),$replace,array_merge(...$items))).'</ul>';
Output
<ul><li>1. COTV_LITE(1800)</li><li>2. COTV_PREMIUM(2200)</li></ul>
Option3
And lastly using an olordered list, which does the numbers for you. In this case we only need the second item from the array (index 1):
$items = [["1.","COTV_LITE(1800)"],["2.","COTV_PREMIUM(2200)"]];
echo '<ol><li>'.implode('</li><li>',array_column($items,1)).'</li></ol>';
Output
<ol><li>COTV_LITE(1800)</li><li>COTV_PREMIUM(2200)</li></ol>
Personally, I would put it in the ol that way you don't have to worry about the order of the numbers, you can let HTML + CSS handle them. Also it's probably the easiest and most semantically correct way, But I don't know if the numbering in the array has any special meaning or not.
In any case I would most definitely put this into a list to render it to HTML. This will give you a lot more options for styling it, later.
Update
want to use option 1. But how do I put each option on a different line using <br>
That one will put the <br> between each array element:
echo implode('<br>',array_merge(...$items));
Output
1.<br>COTV_LITE(1800)<br>2.<br>COTV_PREMIUM(2200)
The only way to easily fix that (while keeping the array_merge) is with preg_replace, which is the second one. So I will call this:
Option 1.2
$items = [["1.","COTV_LITE(1800)"],["2.","COTV_PREMIUM(2200)"]];
echo implode(preg_replace('/^(\w+\(\d+\))$/',' \1<br>',array_merge(...$items)));
Output
1. COTV_LITE(1800)<br>2. COTV_PREMIUM(2200)<br>
Sandbox
Basically there is no way to tell where the end item is after merging them. That operation effectively flattens the array out and gives us something like this:
["1.","COTV_LITE(1800)","2.","COTV_PREMIUM(2200)"]
So that Regex does this 'COTV_PREMIUM(2200)' becomes ' COTV_PREMIUM(2200)<br>'. This is just a way of changing that without having to dip into the array with some logic or something. WE wind up with this modification to the array:
["1."," COTV_LITE(1800)<br>","2."," COTV_PREMIUM(2200)<br>"]
Then with implode we just flatten it again into a string:
"1. COTV_LITE(1800)<br>2. COTV_PREMIUM(2200)<br>"
The Regex ^(\w+\(\d+\))$
^ - Match start of string
(...) - capture group 1
\w+ - match any working character a-zA-Z0-9_ one or more, eg. COTV_PREMIUM
\( - match the ( literally
\d+ - match digits 0-9 one or more, eg 2200
\) - match the ) literally
$ - match end of string
So this matches the pattern of the second (or even) items in the array, then we replace that with this:
The Replacement ' \1<br>'
{space} - adds a leading space
\1 - the value of capture group 1 (from above)
<br> - append a line break
Hope that makes sense. This should work as long as they meet that pattern. Obviously we can adjust the pattern, but with such a small sample size it's hard for me to know what variations will be there.
For example something as simple as (.+\))$ will work TestIt. This one just looks for the ending ). We just need somethng to capture all of the even ones, while not matching the odd. Regular expressions can be very confusing the first few times you see them, but they are extremely powerful.
PS - I added a few links to the function names, these go the the PHP documentation page for them.
Cheers!
Try this
$items = [["1.","COTV_LITE(1800)"],["2.","COTV_PREMIUM(2200)"]];
$imploded = [];
foreach($items as $item) {
$item_entry = implode(' ', $item);
echo $item_entry . '<br/>'; // display items
$imploded[] = $item_entry;
}
// your desired result is in $imploded variable for further use
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,
I am trying to generate a regex that allows me to do the following:
I have a string containing several terms, all which are alphanumeric and maybe some of these special characters: +.#
They are separated by a comma as well.
This is kind of how it looks like:
$string = 'Term1,Term2,Term3,Term4'; ... And so on... (around 60 terms)
I want to be able to get each term and assign it to a variable, because I want to employ a second Regex to a long string, for example:
$secondString = 'This string may contain some terms, such as Term1, or maybe Term2';
So pretty much I want to be able to check if any of the terms in the first string are present in the second string.
I watched the following tutorial:
https://www.youtube.com/watch?v=EkluES9Rvak
But I just seem to not be able to come up with something.
Thank you so much for your help in advance!
Cheers!
You can use array_intersect function after splitting strings into tokens:
$string = 'Term1,Term2,Term3,Term4';
$secondString = 'This string may contain some terms, such as Term1, or maybe Term2';
$arr1 = explode(',', $string);
$arr2 = preg_split('/[,\h]+/', $secondString);
$arr = array_intersect(array_map('strtolower', $arr1), array_map('strtolower', $arr2));
print_r($arr);
Output:
Array
(
[0] => Term1
[1] => Term2
)
I've got a large string that I want to put in an array after each 50 words. I thought about using strsplit to cut, but realised that wont take the words in to consideration, just split when it gets to x char.
I've read about str_word_count but can't work out how to put the two together.
What I've got at the moment is:
$outputArr = str_split($output, 250);
foreach($outputArr as $arOut){
echo $arOut;
echo "<br />";
}
But I want to substitute that to form each item of the array at 50 words instead of 250 characters.
Any help will be much appreciated.
Assuming that str_word_count is sufficient for your needs¹, you can simply call it with 1 as the second parameter and then use array_chunk to group the words in groups of 50:
$words = str_word_count($string, 1);
$chunks = array_chunk($words, 50);
You now have an array of arrays; to join every 50 words together and make it an array of strings you can use
foreach ($chunks as &$chunk) { // important: iterate by reference!
$chunk = implode(' ', $chunk);
}
¹ Most probably it is not. If you want to get what most humans consider acceptable results when processing written language you will have to use preg_split with some suitable regular expression instead.
There's another way:
<?php
$someBigString = <<<SAMPLE
This, actually, is a nice' old'er string, as they said, "divided and conquered".
SAMPLE;
// change this to whatever you need to:
$number_of_words = 7;
$arr = preg_split("#([a-z]+[a-z'-]*(?<!['-]))#i",
$someBigString, $number_of_words + 1, PREG_SPLIT_DELIM_CAPTURE);
$res = implode('', array_slice($arr, 0, $number_of_words * 2));
echo $res;
Demo.
I consider preg_split a better tool (than str_word_count) here. Not because the latter is inflexible (it is not: you can define what symbols can make up a word with its third param), but because preg_split will essentially stop processing the string after getting N items.
The trick, as quite common with this function, is to capture delimiters as well, then use them to reconstruct the string with the first N words (where N is given) AND punctuation marks saved.
(of course, the regex used in my example does not strictly comply to str_word_count locale-dependent behavior. But it still restricts the words to consist of alpha, ' and - symbols, with the latter two not at the beginning and the end of any word).
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.