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);
Related
This question already has answers here:
Insert string at specified position
(11 answers)
separate string in two by given position
(8 answers)
Closed 4 years ago.
I want to explode a string or an integer and separate it by a space.
E.g., I have this int 12345678, and I want its numbers to become like 123 45678. I want the first three numbers separated. Can someone give me a clue or hint in how to achieve this, like what function to use in PHP? I think using an explode will not work here because the explode function needs a separator.
You can use substr_replace() - Replace text within a portion of a string.
echo substr_replace(1234567, " ", 3, 0); // 123 4567
https://3v4l.org/9CFlX
You could use substr() :
$str = "12345678" ;
echo substr($str,0,3)." ".substr($str, 3); // "123 45678"
Also works with an integer :
$int = 12345678 ;
echo substr($int,0,3)." ".substr($int, 3); // "123 45678"
This problem will solve by using substr().
The substr() function returns a part of a string.
Syntax: substr(string,start,length)
Example:
$value = "12345678";
echo substr($value,0,3)." ".substr($value, 3);
Output: 123 45678
You may get better understand from here.
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);
This question already has answers here:
Split a comma-delimited string into an array?
(8 answers)
Closed 7 years ago.
I'm new to php and have a basic question regarding parsing strings.
I have a variable "SKU" whose value is "9897_BLK"
I need to split this into two separate values:
"STYLE" with a value of "9897" AND "COLOR" with a value of "BLK"
I suppose there's a way to use the underscore to delimit the string.
Thanks for your help.
Try explode. This basically separates your string using a delimiter as your first parameter, and the string as the second parameter and returns an array of strings generated. Afterwards you can check if the string was properly parsed or you can just directly assign values just like the one below:
$sku = "9897_BLK";
$sku_parsed = explode("_", $sku);
$style = $sku_parsed[0];
$color = $sku_parsed[1];
If you want more details, the PHP manual is very accessible and has in-depth examples and use-cases for various scenario.
http://php.net/manual/en/function.explode.php
Try this:
$sku = "9897_BLK";
list($style, $color) = explode("_", trim($sku));
In PHP we use an function to split any string with delimiter.
You may try the explode function. The explode function return an array as output and the array values are the delimited values respectively.
Here is code snippet:
$SKU = "9897_BLK";
$DELIMITED_ARRAY = explode("_", $SKU);
$STYLE = $DELIMITED_ARRAY[0];
$COLOR = $DELIMITED_ARRAY[1];
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 9 years ago.
Improve this question
When i read an array i got value set like this "lat" : -37.8087928,. I want to only -37.8087928 part. what is the correct way to do that.
I did it in this way:
$value = '"lat" : -37.8087928,';
$ex = explode(':', $value);
and
$ex2 = explode(',', $ex[1]);
final resualt $ex2[0]
is this correct or what is the correct way, thank you all
$value = '"lat" : -37.8087928,';
$final_value = preg_replace("/[^0-9.\-]/", "", $value);
The code above will strip all characters that are not numeric, dot or hyphen.
You can delete all spaces in a string
$stingname=" test manish ";
str_replace(" ","",$stingname);
echo $stingname;
Result
testmanish
that's object notation. you might want to try
$locations = json_decode($value)
then you could access it like this:
echo $locations->lat; // prints -37.8087928
if you don't want to do that you could do:
$locationArray = explode($value, ':'); // returns [0: 'lat', 1: -37.8087928]
echo trim($locationArray[1]); // prints -37.8087928. trim to get rid of whitespace
The correct method depends on the variability of the input string - "like this" is not an adequate explanation.
Your parser suffices - but has no error handling, nor any means of dealing with a differently formatted string. Using a regexp as described by jorge is more robust, however may not cope with some input scenarios.
The input string you provided looks very like JSON - in which case you should be using a JSON parser - PHP has a very good one built in - which will simply reject non-conformant input.
There is no problem in your approach. But you can use also this which is more easy to understand:
$value = '"lat" : -37.8087928,';
echo $float = filter_var($value, FILTER_SANITIZE_NUMBER_FLOAT,FILTER_FLAG_ALLOW_FRACTION);
Hope this help you!
you can read more about it here
People are suggesting regex's and explodes, why? Thats slow and not needed. If you have a fixed string, you can do it with some string functions:
$value = '"lat" : -37.8087928,';
$result = trim( substr($value, strpos($value,":")+1) ), " ,");
This works by finding the : in that string and substract it till the end. Then with a trim you remove the spaces and the comma. If the comma is ALWAYS there, you can do this, and drop the trim:
$result = substr($value, strpos($value,":")+1), -1 );// till -1 from the end
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]