Split string into array with pattern - php

I send from flex an array to my php script.
String to split is like [F1, 3, true][Urg, 4, false]
I'd to use those information to update record into mySql database.
For example [F1, 3, true] is a record like this [Name, Id, Visible].
But I don't how to split to use information.
Thanks for helping

You can remove the brackets:
$txt = substr($txt, 1, -1);
And explode:
$array = explode(',', $txt)

If you really insist on that format you could try preg_match.
$string = '[F1, 3, true][Urg, 4, false][asd, 1337, TrUe]';
preg_match_all('/\[(\w+),\s*?(\d+),\s*?(true|false)\]/i', $string, $matches, PREG_SET_ORDER);
With this you will get an two-dimensional array, each element in the array is an array. The first element in each array is the matches data row, the following elements are the parsed data.
The elements can be separated by as many whitespace characters as you want, the case of the boolean value does not matter.

I hope there are no commas or square brackets in your data strings - that could make this impossible! But assuming there are none of those:
preg_match_all('/\[([^\]]*)\]/', $text, $matches);
return array_map(function($match) {
return array_map('trim', explode(',', $match));
}, $matches[1]);
(That uses a closure, which is only supported in PHP 5.3 and later; if you are on an older version, you can change it to a foreach loop pretty easily.)

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 get equal parts of multiple strings/array?

I have the following point: a xls file contains one column with codes. The codes have a prefix and a unique code like this:
- VIP-AX757
- VIP-QBHE6
- CODE-IUEF7
- CODE-QDGF3
- VIP-KJQFB
- ...
How can I get equal parts of strings or an array? perfect would be if I get an array like this:
- $result[VIP] = 3;
- $result[CODE] = 2;
An array with the found prefix and the sum of cells with that prefix. But the result is not so important at the moment.
I couldn't find a soloution how to get equal parts of two strings: how to compare this "VIP-AX757" and "VIP-QBHE6" and get a result that says: "VIP-" is the same prefix/part in this two strings?
Hope someone has an idea.
thx!
-drum roll- Time for a one-liner!
$result = array_count_values(array_map(function($v) {list($a) = explode("-",$v); return $a;},$input));
(Assumes $input is your array of codes)
If you are using PHP 5.4 or newer (you should be), then:
$result = array_count_values(array_map(function($v) {return explode("-",$v)[0];},$input));
Tested in PHP CLI:
If the prefix is always followed by a '-' then you can do something like this:-
foreach ($codes as $code) {
$tmp = explode("-",$code);
$result[$tmp[0]] += 1;
}
print_r($result);
Depends on the variability of the data, but something like:
preg_match_all('/^([^-]+)/m', $string, $matches);
$result = array_count_values($matches[1]);
print_r($result);
If you don't know that there is an - after the prefix but the prefix is always letters then:
preg_match_all('/^([A-Z]+)/im', $string, $matches);
$result = array_count_values($matches[1]);
Otherwise you'll have to define exactly what the prefix can contain if it's not the delimiter.
Since you stated via comment to Niet that you don't have a reliable delimiter, then we can only write a pattern that identifies your targeted substrings based on their location in each line.
I recommend preg_match_all() with no capture group, a start of the line anchor, and a multi-line pattern modifier (m).
I've written a preg_split() alternative, but the pattern is a little "clunkier" because of the way I'm handling the line returns.
Code: (Demo)
$string = 'VIP-AX757
VIP-QBHE6
CODE-IUEF7
CODE-QDGF3
VIP-KJQFB';
var_export(array_count_values(preg_match_all('~^[A-Z]+~m', $string, $out) ? $out[0] : []));
echo "\n\n";
var_export(array_count_values(preg_split('~[^A-Z][^\r\n]+\R?~', $string, -1, PREG_SPLIT_NO_EMPTY)));
Output:
array (
'VIP' => 3,
'CODE' => 2,
)
array (
'VIP' => 3,
'CODE' => 2,
)

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...

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.

how to get strings from curly brackets?

I would need help:
I have an array and I need to get values from it...but how to get the data which are within curly brackets ...
It should be something simple, I think ... I tried with explode which obviously cannot work as I have for example within last curly brackets with two kinds of data, which should be distinguished as so...each curly bracket (with data applies to something).
$array = array(
"other" => "{name:2},{value:2},{align:4},{height:4, color:red}",
"another" => "{name:2},{value:2},{align:4},{height:4, color:red}"
);
I'm really struggling ... and appreciate your help.
Thanks
preg_match_all('/\{([^}]*)\}/', $str, $matches);
foreach($matches[1] as $match)
{
$pieces = explode(',', $match);
foreach($pieces as $pair)
{
list($key, $value) = explode(':', trim($pair));
// do something with $key and $value
}
}
On the contrary, I think explode will work perfectly. Explode into separate strings and then for each string retrieve from index 1 to index [arraylength-1] since index 0 contains { and the last index contains }.
$str = substr($str, 1, strlen($str)-1);
So for each string cut out from index 1 to last_index-1.
EDIT:
AFter you do the first explode (which will cut it into 2 big chunks): chunk1 and chunk2
foreach chunk array
$pieces=explode(",",$chunk1); // or chunk 2 (this will further cut the pieces up into strings that were separated by ,)
$str = substr($pieces, 1, strlen($pieces)-1);
Then for each $piece, retrieve the content in between. (pseudo code)
try this, and read about json_decode and json_encode funcitons
$result = json_decode('['.$array['other'].']', true);
UPDATE
after trying this, I've noticed that your string is not a valid JSON, so my answer is not a good solution until you can get {"key":"value"} format

Categories