I have number 123456789.
I want to place - between two number till my given number count would not be end.
$nubmer = 1234567890.
output will be 12-34-56-78-90
function splitNum($num) {
return implode("-", str_split($num, 2));
}
echo splitNum("1234567890") //output: 12-34-56-78-90
Check the Manual for information on str_split and join
<?php
$number = 1234567890;
$split = str_split($number,2);
echo join('-',$split);
?>
You can use simple one liner wordwrap - Wraps a string to a given number of characters:
<?php
$number = 1234567890;
echo wordwrap($number, 2, '-',true);
output:
12-34-56-78-90
You need to convert the number to string and split it into equal part of 2. then implode them. Conversion is not mandatory but good for perfect result.
$nubmer = "1234567890"; //OR $nubmer = 1234567890;
$arr = str_split($nubmer, 2);
echo implode("-", $arr);//12-34-56-78-90
"One-line" solution using chunk_split and trim functions:
$nubmer = "1234567890";
$splitted = trim(chunk_split($nubmer, 2, "-"), "-"); // contains "12-34-56-78-90"
http://php.net/manual/en/function.chunk-split.php
Related
I have a string with numbers, stored in $numbers:
3,6,86,34,43,52
What's the easiest way to get the last value after the last comma? In this case the number 52 would be the last value, which I would like to store in a variable.
The number can vary in size, so trying:
substr($numbers, -X)
does not help me out I think.
This should work for you:
Just use strrpos() to get the position of the last comma and then use substr() to get the string after the last comma, e.g.
$str = "3,6,86,34,43,52";
echo substr($str, strrpos($str, ",") + 1);
output:
52
Just explode the string by the separator character and pick the last of the resulting tokens:
<?php
$string = '3,6,86,34,43,52';
$tokens = explode(',', $string);
echo end($tokens);
An alternative would be to use a regular expression:
<?php
$string = '3,6,86,34,43,52';
preg_match('/,([0-9]+)$/', $string, $tokens);
echo end($tokens);
Personally I have the opinion that efficiency is less important that easy of reading and understanding the code these days. Computation power is cheap, developers are expensive. That is why I would use the first approach, expect when the number of elements in the string gets big.
You can do it like this:
$numbers = "3,6,86,34,43,52";
$arr = explode(",",$numbers);
echo $arr[count($arr)-1];
I'd just explode it to an array, and get the last element:
$numbers = '3,6,86,34,43,52';
$arr = explode(',', $numbers);
echo $arr[count($arr) - 1];
A direct, single-function approach would be to trim every upto the last comma.
Code: (Demo)
$numbers = "3,6,86,34,43,52";
echo preg_replace('/.*,/', '', $numbers);
// 52
I'm new to PHP and I have a problem.
I need delete all chars since a symbol (Sorry for my bad english , i'm from argentina)
I have this text :
3,94€
And I need the text is as follows:
3,94
I tried this by multiple ways but it didn't work.
There are a few ways you can do this:
Using strpos:
$string = '3,94€';
echo substr($string, 0, strpos($string, '&'));
or using strstr:
// Requires PHP 5.3+ due to the true (before_needle) parameter
$string = '3,94€';
echo strstr($string, '&', true);
or using explode:
// Useful if you need to keep the € part for later
$string = '3,94€';
list($part_a, $part_b) = explode('&', $string);
echo $part_a;
or using reset:
$string = '3,94€';
echo reset(explode('&', $string));
The best suited in your case would be to use strpos to find the first occurrence of & in the string, and then use substr to return the string from the begining until the value returned by strpos.
Another posibility is clean the number and then round it:
<?php
//Option 1: with regular expresions:
$val = '3,94€';
$res = preg_replace('/[^0-9.,]/','',$val);
var_dump($res);
//Option 2: with filter functions:
$res2 = filter_var($val, FILTER_SANITIZE_NUMBER_FLOAT, FILTER_FLAG_ALLOW_FRACTION | FILTER_FLAG_ALLOW_THOUSAND);
var_dump($res2);
//Output: 3,948364
//If you want to round it:
$res = substr($res, 0, 4);
var_dump($res);
?>
You can use regex: https://regex101.com/r/uY0kH3/1
It will work in preg_match() function.
You could use str_replace.
<?php
$string = 3,94€
$final = str_replace('€' ,'', $string);
echo $final;
Say I have the following string
$str = "once in a great while a good-idea turns great";
What would be the best solution to creating an array with the array key being the string count of where the word(s) starts?
$str_array['0'] = "once";
$str_array['5'] = "in";
$str_array['8'] = "a";
$str_array['10'] = "great";
$str_array['16'] = "while";
$str_array['22'] = "a";
$str_array['24'] = "good-idea";
$str_array['34'] = "turns";
$str_array['40'] = "great";
As simple as the following:
str_word_count($str, 2);
what str_word_count() does is
str_word_count() — Return information about words used in a string
str_word_count() with 2 as the second argument to get the the offset; and you'd probably need to use the 3rd argument to include hyphen as well as letters in words
$str = "once in a great while a good-idea turns great";
print_r(str_word_count($str, 2));
demo:
http://sandbox.onlinephpfunctions.com/code/9e1afc68725c1472fc595b54c5f8a8abf4620dfc
Try this:
$array = preg_split("/ /",$str,-1,PREG_SPLIT_OFFSET_CAPTURE);
$str_array = Array();
foreach($array as $word) $str_array[$word[1]] = $word[0];
EDIT: Just saw Mark Baker's answer. Probably a better option than mine!
You can use preg_split (with the PREG_SPLIT_OFFSET_CAPTURE option) to split the string on the space, then use the offset it gives you to make a new array.
$str = "once in a great while a good-idea turns great";
$split_array = preg_split('/ /', $str, -1, PREG_SPLIT_OFFSET_CAPTURE);
$str_array = array();
foreach($split_array as $split){
$str_array[$split[1]] = $split[0];
}
I have this string
1010081-COP-8-27-20110616214459
I need to count the last 6 characters starting from the end of this string (because it could may be long starting from the begin)
Then I need to add colons after every 2 characters.
So after counting 6 characters from the end it will be
214459
After having added the colons it will look like:
21:44:59
Can you help me achieving it?
I do not really know where to start!
Thank you
You can do this with substr, str_split and implode
The code is done on multiple lines for clarity, but can easily be done in a chain on one line:
$str = '1010081-COP-8-27-20110616214459';
//Get last 6 chars
$end = substr($str, -6);
//Split string into an array. Each element is 2 chars
$chunks = str_split($end, 2);
//Convert array to string. Each element separated by the given separator.
$result = implode(':', $chunks);
echo preg_replace('/^.*(\d{2})(\d{2})(\d{2})$/', '$1:$2:$3', $string);
It looks to me though like that string has a particular format which you should parse into data. Something like:
sscanf($string, '%u-%3s-%u-%u-%u', $id, $type, $num, $foo, $timestamp);
$timestamp = strtotime($timestamp);
echo date('Y-m-d H:i:s', $timestamp);
If you just want the time:
$time = rtrim(chunk_split(substr($s,-6),2,':'),':');
$final = "1010081-COP-8-27-20110616214459";
$c = substr($final, -2);
$b = substr($final, -4, 2);
$a = substr($final, -6, 2);
echo "$a:$b:$c";
I have written the PHP code for getting some part of a given dynamic sentence, e.g. "this is a test sentence":
substr($sentence,0,12);
I get the output:
this is a te
But i need it stop as a full word instead of splitting a word:
this is a
How can I do that, remembering that $sentence isn't a fixed string (it could be anything)?
use wordwrap
If you're using PHP4, you can simply use split:
$resultArray = split($sentence, " ");
Every element of the array will be one word. Be careful with punctuation though.
explode would be the recommended method in PHP5:
$resultArray = explode(" ", $sentence);
first. use explode on space. Then, count each part + the total assembled string and if it doesn't go over the limit you concat it onto the string with a space.
Try using explode() function.
In your case:
$expl = explode(" ",$sentence);
You'll get your sentence in an array. First word will be $expl[0], second - $expl[1] and so on. To print it out on the screen use:
$n = 10 //words to print
for ($i=0;$i<=$n;$i++) {
print $expl[$i]." ";
}
Create a function that you can re-use at any time. This will look for the last space if the given string's length is greater than the amount of characters you want to trim.
function niceTrim($str, $trimLen) {
$strLen = strlen($str);
if ($strLen > $trimLen) {
$trimStr = substr($str, 0, $trimLen);
return substr($trimStr, 0, strrpos($trimStr, ' '));
}
return $str;
}
$sentence = "this is a test sentence";
echo niceTrim($sentence, 12);
This will print
this is a
as required.
Hope this is the solution you are looking for!
this is just psudo code not php,
char[] sentence="your_sentence";
string new_constructed_sentence="";
string word="";
for(i=0;i<your_limit;i++){
character=sentence[i];
if(character==' ') {new_constructed_sentence+=word;word="";continue}
word+=character;
}
new_constructed_sentence is what you want!!!