Problems with str_split - php

I'm new here, and I have a question. I'm doing a code that I'll use soon, more something left me with a huge doubt. So I'm separating the word more special characters converted are being separated, I wish they would get together to assign a color to each then is there any way to do this?
Code:
<?php
$text = "My nickname is: п€Яd Øwп€d"; #this would be the result of what i received via post
print_r(str_split($text));
?>
Result:
Array
(
[0] => M
[1] => y
[2] =>
[3] => n
[4] => i
[5] => c
[6] => k
[7] => n
[8] => a
[9] => m
[10] => e
[11] =>
[12] => i
[13] => s
[14] => :
[15] =>
[16] => &
[17] => #
[18] => 1
[19] => 0
[20] => 8
[21] => 7
[22] => ;
[23] => &
[24] => e
[25] => u
[26] => r
[27] => o
[28] => ;
[...]
)
I'd like to return this:
Array ( [0] => M
[1] => y
[2] =>
[3] => n
[4] => i
[5] => c
[6] => k
[7] => n
[8] => a
[9] => m
[10] => e
[11] =>
[12] => i
[13] => s
[14] => :
[15] =>
[16] => п
[17] => €
[...]
)
Thank you for the help.
[UPDATED]
I tested the functions that friends have passed, most don't use utf-8 as my default charset ISO-8859-1, and one more thing I forgot to add, by editing the phrase "My nickname is:" and adding a & for example: "My nickname is & personal name" returns a bug. I appreciate who can help again.

You can try to write your own str_split, which could look like the following
function str_split_encodedTogether($text) {
$result = array();
$length = strlen($text);
$tmp = "";
for ($charAt=0; $charAt < $length; $charAt++) {
if ($text[ $charAt ] == '&') {//beginning of special char
$tmp = '&';
} elseif ($text[ $charAt ] == ';') {//end of special char
array_push($result, $tmp.';');
$tmp = "";
} elseif (!empty($tmp)) {//in midst of special char
$tmp .= $text[ $charAt ];
} else {//regular char
array_push($result, $text[ $charAt ]);
}
}
return $result;
}
Basically what it does is check if the current character is a &, if so, save all following characters (including ampersand) in $tmp until ;. This basically gives you the wanted result but will fail, whenever there is a & which doesn't belong to an encoded character.

Use preg_split():
<?php
$text = "My nickname is: п€Яd Øwп€d"; #this would be the result of what i received via post
print_r(preg_split('/(\&(?=[^;]*\s))|(\&[^;]*;)|/', $text, -1, PREG_SPLIT_DELIM_CAPTURE + PREG_SPLIT_NO_EMPTY));
?>

Related

I want all arrays data in one array in php

I want all arrays data in one array not all arrays in one array only the data of all arrays in one array without any other array in php. I have tried to do too many things but still don't work for me.
I also tried
json_encode
with
preg_match
But still don't work for me.
Here is my code
function fetchHashtags($getData){
$body = $getData;
$hashtag_set = [];
$array = explode('#', $body);
foreach ($array as $key => $row) {
$hashtag = [];
if (!empty($row)) {
$hashtag = explode(' ', $row);
$hashtag_set[] = '#' . $hashtag[0];
}
}
print_r($hashtag_set);
}
Output
Array
(
[0] => #Residência
[1] => #architecture
[2] => #casanaserra
[3] => #mountainhouse
[4] => #interiores
[5] => #decoration
[6] => #casanaserra
[7] => #casadecampo
[8] => #construção
[9] => #exterior
[10] => #rustico
[11] => #arpuro
[12] => #home
[13] => #riodejaneiro
[14] => #construir
[15] => #casasincriveis
[16] => #outdoor
[17] => #arquiteto
[18] => #casasincriveis
[19] => #montanhas
[20] => #archdaily
[21] => #architecturelovers
[22] => #arqlovers
[23] => #arqlove
[24] => #homedesign
[25] => #arquiteturaedecoração
)
Array
(
[0] => #We
[1] => #ascaspenvswheaton
)
Array
(
[0] => #شجریان_بشنویم...
[1] => #۰
[2] => #شجریان_بشنویم
[3] => #_
[4] => #شجریانیها
[5] => #همایون_شجریان
[6] => #مژگان_شجریان
[7] => #پرویزمشکاتیان
[8] => #موزیک
[9] => #سهراب_پورناظری
[10] => #محمدرضا_شجریان
[11] => #موزیک_ویدیو
[12] => #ایران
[13] => #ترانه_ماندگار
[14] => #تصنیف
[15] => #آهنگ_ایرانی
[16] => #هنر
[17] => #موسیقی_ایرانی
[18] => #شعروشاعری
[19] => #موسیقی_سنتی_ایران
[20] => #آواز_سنتی
[21] => #قدیمیها
[22] => #دلشدگان
[23] => #دلنشین
[24] => #سینما
[25] => #homayoun_shajarian
[26] => #music
[27] => #mohamadrezashajarian
[28] => #home
[29] => #iran
[30] => #shajarian
)
And one more thing i also want to remove some data that don't look like hashtags.
for example:
Array
(
[0] => #Residência
[1] => architecture // This should be removed
[2] => #casanaserra
[3] => mountainhouse // This also should be removed
[4] => #interiores
)
As you can see from my code you can use array_merge for merge arrays then use array_filter for filter value without # or other rules you need:
$array = [['1', '#2', '3', '#4'], ['5', '#6']];
$flatArray = array_merge(...$array);
$filteredArray = array_filter($flatArray, function($a) {
if (str_contains($a, '#')) {
return $a;
}
});
print_r($filteredArray);
Result:
Array (
[1] => #2
[3] => #4
[5] => #6 )
Reference:
array_merge
array_filter
str_contains
After seeing your code and the context of the situation I changed things:
Instead of use explode i used preg_split for split \n and space;
Delete array_map because you don't need it.
$array = ["
My name is Faraz shaikh i am a php developer and this my #instagram profile.Check out my #merge and my #packages with new #hashtags
#chinese #art #colors #home #harmory #peace #handmade #paintings #etsy
", "
My name is Hunain shaikh i am a php developer and this my #Facebook profile.Check out my #Berge and my #Hackages with new #tags
#english #Kite #colours #me #memory #pee #made #paints #etsafsy
"];
function fetchHashtags($getData) { // This Functions takes out the hashtags from the string and put it in to arrays.
$body = $getData;
$hashtag_set = [];
$array = preg_split('/[\s]+/', $body);
$mapArray = array_map(function($a) {
return str_replace(' ', '', $a);
}, $array);
$filteredArray = array_filter($mapArray, function($a) {
if (str_contains($a, '#')) {
return $a;
}
});
return $filteredArray;
}
$recentNumberOfPosts = 1;
$zeroPost = 0; //Get Post from 0 to recentNumberOfPosts | NOTE: default = 4
$finalArr = [];
while ($zeroPost <= $recentNumberOfPosts) {
// fetchHashtags($hashtagRecent['data'][$zeroPost]['caption']);
$finalArr[] = fetchHashtags($array[$zeroPost]);
$zeroPost++;
}
print_r(array_merge(...$finalArr));
Fiddle

Array to String After Two Elements

I have this array:
Array (
[0] => 1
[1] => 0
[2] => 0.32593699614063
[3] => -0.010875407736967
[4] => 0.32593699614063
[5] => 0.325936996140630.32593699614063
[6] => 0.1135301278
[7] => -0.028758634562
[8] => 0.044068247856859
[9] => -0.028758634562
[10] => 0
[11] => -0.01759558330449
[12] => 0
[13] => 0
[14] => 0
[15] => 0.05005732991382
[16] => 0.17093532486612
[17] => 0.098872325264
[18] => 0.346220929
[19] => 0.098872325264
[20] => 0.38405017865388
[21] => 0.098872325264
[22] => 0.64744282045057
[23] => 0.098872325264
[24] => 1
[25] => 0
)
I need to convert it to the following string:
1 0, 0.32593699614063 -0.010875407736967, 0.32593699614063 0.32593699614063, etc.
In other words, there should be a comma after every two elements.
Can you suggest the php code? Currently I have string without commas after every two elements.
Code:
$od = array_flatten($MultiDimensional)
$result = implode(" ",$od);
Output:
1 0 0.32593699614063 -0.010875407736967 0.32593699614063 -0.028758634562 0.1135301278 -0.028758634562 0.044068247856859
You can use array_chunk with implode
$arr = [1,2,3,4,5,6,7,8,9,10];
$res= '';
foreach(array_chunk($arr, 2) as $key => $value){
$res .= ($key < count(array_chunk($arr, 2))-1) ? (implode(' ',$value).",") : implode(' ',$value);
}
Live Demo
You can combine array_chunk, array_map and implode :
$od = array(1, 0, 0.32593699614063, -0.010875407736967, 0.32593699614063, -0.028758634562, 0.1135301278, -0.028758634562, 0.044068247856859);
echo implode(',' , // each pair is separated by a comma
array_map(function($pair){return implode(' ', $pair);}, // each element in pair separated by a space
array_chunk($od, 2) // cut original array in blocks of 2 items
)
);

Finding MAX value of raw CSV data for specific column in PHP

Using cURL:
$url = $some_site;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$output = curl_exec($ch);
curl_close($ch);
where the '$output' variable contains the following 7 columns (# of rows will vary):
1,a,6045,6168,6731,6847,522800
2,b,7847,8124,7645,7716,614400
3,c,7288,7633,7150,7442,801800
4,d,5546,5791,5460,5581,554200
5,e,4579,4679,4359,4572,557400
etc ...
As you can see, in the 4th column, the numbers are:
6168
8124
7633
5791
4679
And the highest number is: 8124
I am trying to figure out how to parse the '$output' variable so I can evaluate all the numbers in the 4th column to determine the high.
I have tried:
$csv = array_map('str_getcsv', $output);
echo max($csv[4]);
But nothing is returned
If you output your $csv value you will see that it is array with structure like:
...
[2] => Array
(
[0] => 3
[1] => c
[2] => 7288
[3] => 7633
[4] => 7150
[5] => 7442
[6] => 801800
)
[3] => Array
(
[0] => 4
[1] => d
[2] => 5546
[3] => 5791
[4] => 5460
[5] => 5581
[6] => 554200
)
[4] => Array
(
[0] => 5
[1] => e
[2] => 4579
[3] => 4679
[4] => 4359
[5] => 4572
[6] => 557400
)
....
So your $csv[4] is not a list of values from column 4. It's the 5th element of your array. So you need to go further, either with a simple foreach:
$max = 0;
foreach ($csv as $row) {
// use index `3` because numeration starts with `0`
if ($max < $row[3]) {
$max = $row[3];
}
}
Or with array_column (since php5.5):
// take all values witn index `3` and find max
echo max(array_column($csv, 3));
In both cases it is 8124
It's because str_getcsv not following standards, and from output You have a "broken array"... I suppose that it may look like this:
Array
(
[0] => 1
[1] => a
[2] => 6045
[3] => 6168
[4] => 6731
[5] => 6847
[6] => 522800
2
[7] => b
[8] => 7847
[9] => 8124
[10] => 7645
[11] => 7716
[12] => 614400
3
[13] => c
[14] => 7288
[15] => 7633
[16] => 7150
[17] => 7442
[18] => 801800
4
[19] => d
[20] => 5546
[21] => 5791
[22] => 5460
[23] => 5581
[24] => 554200
5
[25] => e
[26] => 4579
[27] => 4679
[28] => 4359
[29] => 4572
[30] => 557400
)
http://sandbox.onlinephpfunctions.com/code/b5834d98eda11b1726adc9ef1b7592f9ba32242c
You can do it like this:
<?php
// $csv is just a string ... output from Your curl will be same I think
$csv = <<<EOT
1,a,6045,6168,6731,6847,522800
2,b,7847,8124,7645,7716,614400
3,c,7288,7633,7150,7442,801800
4,d,5546,5791,5460,5581,554200
5,e,4579,4679,4359,4572,557400
EOT;
function csv2array($csv) {
$csv = str_getcsv($csv, PHP_EOL);
return array_map('str_getcsv', $csv);
}
function findMaxInColumn($array, $column = 3) {
return max(array_column($array, $column));
}
$parsedCsv = csv2array($csv);
print_r(findMaxInColumn($parsedCsv));
http://sandbox.onlinephpfunctions.com/code/82020f0d85acf8d6b15b5e7fd78a8d1a80618ff2

PHP Array Keys to variables

I want a value of my array to be displayed if I use a equel or almost equel variable.
So for example if I have the following array line: [1] => g
I want to display 'g' if I use the variable $1 (Or even better with the varible $arr1, so it does not interfere with other things later on.)
Here is my code: (I'm uploading a simple .txt file with some letters and making a array of each individual charachter):
$linearray = array();
$workingarray = array();
while(! feof($file)) {
$line = fgets($file);
$line = str_split(trim("$line"));
$linearray = array_merge($linearray, $line);
}
$workingarray[] = $linearray;
print_r($workingarray);
When I have done this I will get this outcome;
Array ( [0] => Array ( [0] => g [1] => g [2] => h [3] => o [4] => n
[5] => d [6] => x [7] => s [8] => v [9] => i [10] => s [11] => h [12]
=> f [13] => g [14] => f [15] => h [16] => m [17] => a [18] => g [19] => i [20] => e [21] => d [22] => h [23] => v [24] => b [25] => v [26] => m [27] => d [28] => o [29] => m [30] => v [31] => b [32] => ) )
I tried using the following to make it work:
extract($workingarray);
echo "$1";
But that sadly doesn't work. I just recieve this:
$1
And I want to recieve this:
g
It would be even better if I recieved the same effect with for example echo "$arr1" and then recieve g and for echo "$arr2" recieve h etc etc
This is simply impossible: http://php.net/manual/en/language.variables.basics.php
Variable names cannot start with a digit. The only allowable first char for variable names are letters and underscore.
And don't use extract or similar constructs. All they do is litter your variable namespace with unpredictable/unknown junk - you could very easily overwrite some OTHER critical variable with this useless junk, making for very difficult/impossible bugs to diagnose.
You're not saving any time by making up these new variables.

How to split Chinese characters in PHP?

I need some help regarding how to split Chinese characters mixed with English words and numbers in PHP.
For example, if I read
FrontPage 2000中文版應用大全
I'm hoping to get
FrontPage, 2000, 中,文,版,應,用,大,全
or
FrontPage, 2,0,0,0, 中,文,版,應,用,大,全
How can I achieve this?
Thanks in advance :)
Assuming you are using UTF-8 (or you can convert it to UTF-8 using Iconv or some other tools), then using the u modifier (doc: http://www.php.net/manual/en/reference.pcre.pattern.modifiers.php )
<?
$s = "FrontPage 2000中文版應用大全";
print_r(preg_match_all('/./u', $s, $matches));
echo "\n";
print_r($matches);
?>
will give
21
Array
(
[0] => Array
(
[0] => F
[1] => r
[2] => o
[3] => n
[4] => t
[5] => P
[6] => a
[7] => g
[8] => e
[9] =>
[10] => 2
[11] => 0
[12] => 0
[13] => 0
[14] => 中
[15] => 文
[16] => 版
[17] => 應
[18] => 用
[19] => 大
[20] => 全
)
)
Note that my source code is stored in a file encoded in UTF-8 also, for the $s to contain those characters.
The following will match alphanumeric as a group:
<?
$s = "FrontPage 2000中文版應用大全";
print_r(preg_match_all('/(\w+)|(.)/u', $s, $matches));
echo "\n";
print_r($matches[0]);
?>
result:
10
Array
(
[0] => FrontPage
[1] =>
[2] => 2000
[3] => 中
[4] => 文
[5] => 版
[6] => 應
[7] => 用
[8] => 大
[9] => 全
)
/**
* Reference: http://www.regular-expressions.info/unicode.html
* Korean: Hangul
* CJK: Han
* Japanese: Hiragana, Katakana
* Flag u required
*/
preg_match_all(
'/\p{Hangul}|\p{Hiragana}|\p{Han}|\p{Katakana}|(\p{Latin}+)|(\p{Cyrillic}+)/u',
$str,
$result
);
This one is working if you are using PHP 7.0 too.
This one is just not working. I regret I have upvoted a non-working solution....
<?
$s = "FrontPage 2000中文版應用大全";
print_r(preg_match_all('/(\w+)|(.)/u', $s, $matches));
echo "\n";
print_r($matches[0]);
?>
With this code you can make chinese text (utf8) to wrap at the end of the line so that it is still readable
print_r(preg_match_all('/([\w]+)|(.)/u', $str, $matches));
$arr_result = array();
foreach ($matches[0] as $key => $val) {
$arr_result[]=$val;
$arr_result[]="​"; //add Zero-Width Space
}
foreach ($arr_result as $key => $val) {
$out .= $val;
}
return $out;

Categories