This question already has answers here:
remove duplicate from string in PHP
(2 answers)
Closed 5 years ago.
Below is the variable I have,
$string = 'AAA,BBB,aAA,BbB,AAA,BbB';
I need the unique string result below,
$string = 'AAA,BBB,aAA,BbB';
How to make it unique just like array_unique() function , is there any default String function to remove duplicate string in PHP?
I don't know if php have such function, but you can process it like this: live demo
$raw = 'AAA,BBB,aAA,BbB,AAA,BbB';
$string = implode(',', array_unique(explode(',', $raw)));
For the record, I fully support Kris' method, and that is the way I would choose if this were for my project. However, I would just like to add that there are several additional ways to skin this cat:
Code: (Demo)
$raw = 'AAA,BBB,aAA,BbB,BbB,AAA';
// str_word_count() -> array_unique() -> implode()
echo implode(',',array_unique(str_word_count($raw,1)));
echo "\n";
// str_getcsv() -> array_unique() -> implode()
echo implode(',',array_unique(str_getcsv($raw)));
echo "\n";
// preg_match_all() -> array_unique() -> join()
echo join(',',array_unique(preg_match_all("/[A-Za-z]{3}/",$raw,$m)?$m[0]:array()));
echo "\n";
// preg_split() -> array_unique() -> join()
echo join(',',array_unique(preg_split("/,/",$raw)));
echo "\n";
// preg_replace() -> parse_str() -> implode()
parse_str(preg_replace('/(^|,)([A-Za-z]{3})/',"$2=$2&",$raw),$array);
echo implode(',',$array);
I have 5 different methods to explode the csv string without using explode().
1 method that doesn't use array_unique.
And of course implode() and join() can be used interchangeably as they are synonyms.
I think the fifth method is my favorite as it is the wackiest and doesn't use array_unique(). *unfortunately it's a two-liner :{
p.s.
#Thiyagu says this is how the string is constructed:
forloop(){ $string .= $a[i].',';}
If that is true, then weeding out the duplicates can be done inside this loop by leveraging a temporary array. This has the added benefit of omitting the trailing comma that concatenation generates.
foreach($data as $value){
$result[$value]=$value; // duplicate values will be overwritten because arrays may not have two identical keys
}
echo implode(',',$result);
Related
This question already has answers here:
implode() string, but also append the glue at the end
(6 answers)
Closed 1 year ago.
I have this sentence:
piece:5,dozen:10
and I need to print it via php like this:
piece:5$,dozen:10$
without editing the line in the editor, I need php to do it automatically. Now I thought to split it like this:
$uom = "piece:5,dozen:10";
$lst1 = explode(',', $uom);
var_dump($lst1);
and it returned like this:
array (size=2)
0 => string 'piece:5' (length=7)
1 => string 'dozen:10' (length=8)
which is ok for now, so I need after each string piece:5$ dozen:10$ and then I did this:
$lst2 = implode('$ ', $lst1);
echo $lst2;
It printed:
piece:5$ dozen:10
I need the $ to be printed also after 10, so it will be like this:
piece:5$ dozen:10$
What is the right way to do this? What did I do wrong? What if the values are dynamically coming from the database?
You can use a combination of explode, array_map and implode like so:
<?php
$uom = 'piece:5,dozen:10';
$add_dollars = array_map(function($e) {
return $e . '$';
}, explode(',', $uom));
echo implode(" ", $add_dollars);
I see few explode-implode answers. I don't want to duplicate answer, so let me do it another way – with regex.
$data = "piece:5,dozen:10";
echo preg_replace("/(\d+)/i", "$1\$", $data);
It may be a good idea to make it a bit more complex, i.e. take not only \d+, but also previous string and colon. Rather without(!) comma. In my opinion this may be better (because it's usually worth to be strict in regex):
$data = "piece:5,dozen:10";
echo preg_replace("/([a-zA-Z]:\d+)/i", "$1\$", $data);
I encourage you to read php manual: preg_replace.
Answering also the question about jQuery – you don't need to use jQuery, you can do that in pure javascript. And it will be really similar! For example:
let data = "piece:5,dozen:10";
let modified = data.replace(/([a-zAZ]:\d+)/g,"$1\$");
console.log(modified);
this is my first post. sorry if i did something wrong...
anyways i have a file that gets updates by php and this is EXACTLY it:
31\n
127\n
131\n
124\n
144\n
142\n
133\n
133\n
9\n
0\n
22\n
18\n
i made this script in php:
$logContents = file_get_contents("logs/mainlog.txt");
$logitemArray = explode("\n", $logContents);
echo max($logitemArray);
but it echos 9. why? it said in the php documentation that max() should return the biggest value in the array
thanks in advance
explode() returns an array of strings, so they're being compared lexicographically. You need to convert them to numbers so that max() will compare them numerically.
$logitemArray = array_map('intval', explode("\n", $logContents));
echo max($logitemArray);
BTW, you can use the file() function to read a file directly into an array of lines, instead of using file_get_contents() followed by explode().
$logitemArray = array_map('intval', file("logs/mainlog.txt", FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES));
Like the comments have said, it's because 9 is the largest lexigraphical value. If it said 900 it would still be the same.
This is because when you split the string with explode you get an array of type string. The following code will convert the elements in the array to integers which should give expected behaviour.
$logitemArray = array_map('intval', explode("\n", $logContents));
This question already has answers here:
Fastest way of deleting a value in a comma separated list
(4 answers)
Closed 2 years ago.
I am storing numbers in a database with a string like 5,55,15,17,2,35
I want to remove say number 5 from the string, keeping the comma seperation set like it is.
The problem with using str_replace() is that all of the 5's will be removed. If i use str_replace('5,'', $string) thats fine, but the comma wouldn't be after the 5 if it was in the middle of the string or at the end. That same str_replace would also remove part of 15, and 55,
Am i missing something?
$array = explode(',', $string);
foreach ($array as $k => $v)
if ($v == 5) unset($array[$k]);
$string = implode(',', $array);
You probably shouldn't be storing a comma separated list of values in a single database column in the first place. It looks like a one-to-many association, which should be modeled with a separate table.
Split the string first by comma so you can work with the numbers directly. Remove 5 from the array, then recombine the array into a comma-delimited string.
Here's an example:
<?php
$input = '5,55,15,17,2,35';
echo "Input: $input<br />";
// Split the string by "exploding" the string on the delimiter character
$nums = explode(',', $input);
// Remove items by comparing to an array containing unwanted elements
$nums = array_diff($nums, array(5));
// Combine the array back into a comma-delimited string
$output = implode(',', $nums);
echo "Output: $output<br />";
// Outputs:
// Input: 5,55,15,17,2,35
// Output: 55,15,17,2,35
?>
str_replace([$num.",",",".$num],"",$input);
U can try something like this:
// Convert string into array of numbers
$arrOfNumbers = explode(',', $string);
// Find id of number for del
$numberForDelId = array_search($numberForDel, $arrOfNumbers);
//Delete number
unset($arrOfNumbers[$numberForDelId]);
// Convert back to string
$resultString = implode(',' $arrOfNumbers)
You should:
get the string
then "explode" the values into an array
and re-create the string without the number you want to remove.
This question already has answers here:
Php compare strings and return common values
(3 answers)
Closed 8 years ago.
I have two strings of keywords
$keystring1 = "tech,php,radio,love";
$keystring2 = "Mtn,huntung,php,tv,tech";
How do i do return keywords that common in both strings
You can do this:
$common = array_intersect(explode(",", $keystring1), explode(",", $keystring2));
If you want them back into strings, you can just implode it back.
Hmm, interesting question... You can use this.
$arr1 = explode(',',$keystring1);
$arr2 = explode(',',$keystring2);
$duplicates = array_intersect($arr1,$arr2);
foreach($duplicates as $word) {
echo $word;
}
You could explode() both strings on commas into arrays and loop through the first array checking to see if any of the words exist in the second array using the in_array() function. If so then add that word to a "common words" array.
Those are going to need to be arrays not variables.
$keystring1 = array('tech','php','radio','love');
$keystring2 = array('mtn','huntung','php','tv','tech');
First of all...
This question already has an answer here:
How to unserialize an ArrayObject
(1 answer)
Closed 1 year ago.
I'm trying to parse the 2 values contained within double quotes from a session string. The other string variables are not constant and therefore can not use any additional characters as markers. I only need the quoted values. My following sscanf function is incomplete.
$string = 'a:1:{s:14:"174.29.144.241";s:8:"20110508";}';
sscanf($string,'%[^"]', $login_ip, $login_date);
echo $login_ip;
echo $login_date;
Thanks for your help.
That data is just PHP serialized text from serialize()
In which case you can get at the data you need with:
$sessionData = unserialize('a:1:{s:14:"174.29.144.241";s:8:"20110508";}');
list($ip, $date) = each($sessionData);
$string = 'a:1:{s:14:"174.29.144.241";s:8:"20110508";}';
preg_matches("/(\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b)/",$string,$matches);
echo $matches[1];
This should return your ip address. consult php.net
You can use regex to do that.
$string = 'a:1:{s:14:"174.29.144.241";s:8:"20110508";}';
$pattern = '/"(?P<ip>[^"]*)"[^"]*"(?P<date>[^"]*)"/';
preg_match( $pattern, $string, $matches );
echo $matches['ip'].' '.$matches['date'];
First quoted value will go to ip, second to date.
An interesting hack would be to use explode using " as the separator like this:
<?php
$res = explode('"','a:1:{s:14:"174.29.144.241";s:8:"20110508";}');
print_r($res);
?>
Any value in double quotes would be returned in an odd index i.e $res[1], $res[3]