how can i convert it into float and then increment it and then convert back to string.
if($set==$Data_Id)
{
$rel='1.1.1.2';
}
after increment it should be like 1.1.1.3.
Please any help.
so crazy, it may work
$rel='1.1.1.2';
echo substr($rel, 0, -1). (substr($rel,-1)+1); //1.1.1.3
the big question is what do you want to happen if the string ends in 9 ??
Here's a slightly different approach.
<?php
function increment_revision($version) {
return preg_replace_callback('~[0-9]+$~', function($match) {
return ++$match[0];
}, $version);
}
echo increment_revision('1.2.3.4'); //1.2.3.5
Anthony.
"1.1.1.2" is not a valid number. So you'll have to do something like this:
$rel = '1.1.1.2';
$relPlusOne = increment($rel);
function increment($number) {
$parts = explode('.', $number);
$parts[count($parts) - 1]++;
return implode('.', $parts);
}
If this is exactly the case you need to solve, you could do it with intval(), strval(), str_replace(), substr() and strlen().
$rel = '1.1.1.2'; // '1.1.1.2'
// replace dots with empty strings
$rel = str_replace('.', '', $rel); // '1112'
// get the integer value
$num = intval($rel); // 1112
// add 1
$num += 1; // 1113
// convert it back to a string
$str = strval($num); // '1113'
// initialize the return value
$ret = '';
// for each letter in $str
for ($i=0; $i<strlen($str); $i++) {
echo "Current ret: $ret<br>";
$ret .= $str[$i] . '.'; // append the current letter, then append a dot
}
$ret = substr($ret, 0, -1); // remove the last dot
echo "Incremented value: " . $ret;
This method will change 1.1.1.9 to 1.1.2.0, however. If that's what you want, then this will be fine.
Related
Is there a way to trim a text string in PHP so it has a certain number of characters? For instance, if I had the string:
$string = "this is a string";
How could I trim it to say:
$newstring = "this is";
This is what I have so far, using chunk_split(), but it isn't working. Can anyone improve on my method?
function trimtext($text)
{
$newtext = chunk_split($text,15);
return $newtext;
}
I also looked at this question, but I don't really understand it.
if (strlen($yourString) > 15) // if you want...
{
$maxLength = 14;
$yourString = substr($yourString, 0, $maxLength);
}
will do the job.
Take a look here.
substr cuts words in half. Also if word contains UTF8 characters, it misbehaves. So it would be better to use mb_substr:
$string = mb_substr('word word word word', 0, 10, 'utf8').'...';
You didn't say the reason for this but think about what you want to achieve. Here is a function for shorten a string word by word with or without adding ellipses at the end:
function limitStrlen($input, $length, $ellipses = true, $strip_html = true) {
//strip tags, if desired
if ($strip_html) {
$input = strip_tags($input);
}
//no need to trim, already shorter than trim length
if (strlen($input) <= $length) {
return $input;
}
//find last space within length
$last_space = strrpos(substr($input, 0, $length), ' ');
if($last_space !== false) {
$trimmed_text = substr($input, 0, $last_space);
} else {
$trimmed_text = substr($input, 0, $length);
}
//add ellipses (...)
if ($ellipses) {
$trimmed_text .= '...';
}
return $trimmed_text;
}
function trimtext($text, $start, $len)
{
return substr($text, $start, $len);
}
You can call the function like this:
$string = trimtext("this is a string", 0, 10);
Would return:
This is a
substr let's you take a portion of string consisting of exactly as much characters as you need.
You can use this
substr()
function to get substring
If you want to get a string with a certain number of characters you can use substr, i.e.
$newtext = substr($string,0,$length);
where $length is the given length of the new string.
If you want an abstract for the first 10 words (you can use html in $text, before script there is strip_tags)
use this code:
preg_match('/^([^.!?\s]*[\.!?\s]+){0,10}/', strip_tags($text), $abstract);
echo $abstract[0];
My function has some length to it, but I like to use it. I convert the string int to a Array.
function truncate($text, $limit){
//Set Up
$array = [];
$count = -1;
//Turning String into an Array
$split_text = explode(" ", $text);
//Loop for the length of words you want
while($count < $limit - 1){
$count++;
$array[] = $split_text[$count];
}
//Converting Array back into a String
$text = implode(" ", $array);
return $text." ...";
}
Or if the text is coming from an editor and you want to strip out the HTML tags.
function truncate($text, $limit){
//Set Up
$array = [];
$count = -1;
$text = filter_var($text, FILTER_SANITIZE_STRING);
//Turning String into an Array
$split_text = preg_split('/\s+/', $text);
//Loop for the length of words you want
while($count < $limit){
$count++;
$array[] = $split_text[$count];
}
//Converting Array back into a String
$text = implode(" ", $array);
return $text." ...";
}
With elipsis (...) only if longer - and taking care of special language-specific characters:
mb_strlen($text,'UTF-8') > 60 ? mb_substr($text, 0, 60,'UTF-8') . "…" : $text;
I want to parse and expand the given strings in PHP.
From
0605052&&-5&-7&-8
0605052&&-4&-7
0605050&&-2&-4&-6&-8
To
0605052, 0605053 ,0605054 ,0605055, 0605057, 0605058
0605052,0605053,0605054,0605057
0605050,0605051,0605052,0605054,0605056,0605058
can someone help me with that? thanks in advance!
Your question is not very clear, but I think you mean a solution like this:
Edited: Now the hole ranges were shown and not only the specified numbers.
<?php
$string = "0605052&&-5&-7&-8";
$test = '/^([0-9]+)\&+/';
preg_match($test, $string, $res);
if (isset($res[1]))
{
$nr = $res[1];
$test = '/\&\-([0-9])/';
preg_match_all($test, $string, $res);
$result[] = $nr;
$nrPart = substr($nr, 0, -1);
$firstPart = substr($nr, -1);
if (isset($res[1]))
{
foreach ($res[1] as &$value)
{
if ($firstPart !== false)
{
for ($i=$firstPart+1; $i<=$value; $i++)
{
$nr = $nrPart . $i;
$result[] = $nr;
}
$firstPart = false;
}
else
{
$nr = $nrPart . $value;
$result[] = $nr;
$firstPart = $value;
}
}
}
var_dump($result);
}
?>
This delivers:
result[0] = "0605052"
result[1] = "0605053"
result[2] = "0605054"
result[3] = "0605055"
result[4] = "0605057"
result[5] = "0605058"
I think a multi step approach is the best thing to do here.
E.g. take this as an example 0605052&&-5&-7&-8:
Split at -. The result will be 0605052&&, 5&, 7&, 8
The first result 0605052&& will help you create your base. Simply substring the numbers by finding first occurence of & and substring to the next to last number. Result will be 060505. You will also need the last number, so get it as well (which is 2 in this case).
Get the remaining ends now, all \d& are simple to get, simply take the first character of the string (or if those can be more than one number, use substring with first occurence of & approach again).
The last number is simple: it is 8.
Now you got all important values. You can generate your result:
The last number from 2., all numbers from 3. and the number from 4. together with your base are the first part. In addition, you need to generate all numbers from the last number of 2. and the first result of 3. in a loop by a step of 1 and append it to your base.
Example Code:
<?php
$str = '0605052&&-5&-7&-8';
$split = explode('-', $str);
$firstAmpBase = strpos($split[0], '&');
$base = substr($split[0], 0, $firstAmpBase - 1);
$firstEnd = substr($split[0], $firstAmpBase - 1, 1);
$ends = [];
$firstSingleNumber = substr($split[1], 0, strpos($split[1], '&'));
for ($i = $firstEnd; $i < $firstSingleNumber; $i++) {
array_push($ends, $i);
}
array_push($ends, $firstSingleNumber);
for ($i = 2; $i < count($split) - 1; $i++) {
array_push($ends, substr($split[$i], 0, strpos($split[$i], '&')));
}
array_push($ends, $split[count($split) - 1]);
foreach ($ends as $end) {
echo $base . $end . '<br>';
}
?>
Output:
0605052
0605053
0605054
0605055
0605057
0605058
I'm trying to parse a string and delete the adjacent letters that are same. I want to return the count of number of deletions and output the resulted string after the deletions are made. Say I have
$str = "aaabbbcc";
As you can see, you need to do 5 deletions to make the adjacent letters not same. The $output string is "abc" and the number of deletions is five.
function str_deletions ($str)
{
$prev = $str[0];
$length = strlen($str);
$deletions = 0;
$output = "";
for ($i=1 ; $i < $length; $i++)
{
if ($str[$i]== $prev)
{
$deletions++;
$prev = $str[$i]; // not sure here ?
}
}
echo $output; // ?
return $deletions;
}
$str = "aabbcc";
echo str_deletions ($str);
EDIT
This is an interview question, I'm not supposed to use any built-in functions like regex or array_count_values
Thanks for your help !
Here is another regex solution. I use a regex to only match a word character that is repeated, and then remove each consecutive repeating character one by one, which allows me to use &$count argument with preg_replace:
count
If specified, this variable will be filled with the number of replacements done.
The regex is
(\w)(?=\1)
See demo. Note you can replace \w with . to match any character but a newline. OR if you need to match only letters, I suggest using '/(\p{L})(?=\1)/u'
See IDEONE demo:
$str = "aaabbbcc";
$cnt = -1;
$result = preg_replace('/(\w)(?=\1)/', "", $str, -1, $cnt);
echo "Result: " . $result . PHP_EOL . "Deletions: " . $cnt;
Output:
Result: abc
Deletions: 5
Regex solution
This is a much simpler way of doing what you're after using preg_replace():
<?php
function str_deletions($str){
$replaced = preg_replace("/(.)\\1+/", "", $str);
$length = strlen($str) - strlen($replaced);
return array("new_word" => $replaced, "chars_replaced" => $length);
}
$str = "aabbcc";
$string_deletions = str_deletions($str);
echo "New String: " . $string_deletions['new_word'] . "\n";
echo "Chars deleted: " . $string_deletions['chars_replaced'] . "\n";
?>
No inbuilt functions
For the purposes of completion (and since you updated your question with more information to say that we can't use regexes because it's an interview question), here's what I'd do:
Using count_chars():
function str_deletions($str){
$string_data['new_word'] = count_chars($str,3);
$string_data['chars_replaced'] = strlen($str) - strlen($string_data['new_word']);
return $string_data;
}
$str = "aabbcc";
echo str_deletions($str);
Note: in this example count_chars(); will return unique chars in a string, not quite remove duplicates (i.e. "aabbccaa" would still yield "abc" as an output) but your question wasn't clear what the interviewer wanted - whether it was truly a remove duplicate question or a unique char question.
Using array_unique():
Slightly slower and a bit more heavy handed:
function str_deletions($str){
$string_array = array_unique(str_split($str));
foreach($string_array as $string_cur){
$string_data['new_word'] .= $string_cur;
}
$string_data['chars_replaced'] = strlen($str) - strlen($string_data['new_word']);
return $string_data;
}
$str = "aabbcc";
echo str_deletions($str);
Note: It's worth pointing out that if I realised it was an interview question, I wouldn't have provided an answer as doing it for you kind of defeats the purpose. Still, with the amount of answers here now and the fact that I've seen something similar to this in an interview, my hope is someone will learn from these.
The basic algorithm (indeed $prev = $str[$i]; isn't at the good place but you wasn't far):
function str_deletion($str) {
$del = 0;
if (1 < $length = strlen($str)) { // $str has more than 1 char
$prev = $str[0];
$output = $prev;
for ($i=1; $i<$length; $i++) {
if ($prev == $str[$i]) {
$del++;
} else {
$prev = $str[$i]; // when different, change the previous character
$output .= $prev; // and append it to the output
}
}
} else {
$output = $str;
}
echo $output;
return $del;
}
I have changed your function
this is not returning both the output string and number of deletions
function str_deletions ($str)
{
$prev = NULL;
$deletions = 0;
$output = "";
$i=0;
while ($i < strlen($str))
{
if (substr($str,$i,1) == $prev)
{
$deletions++;
//$prev = substr($str,$i,1);/*remove this line, no need here as the same stmnt is there after ifelse*/
}else{
$output.=substr($str,$i,1);
}
$prev = substr($str,$i,1);
$i++;
}
$arr = array(
'output'=>$output,
'deletions'=>$deletions
);
return $arr;
}
$str = "aaabbcc";
print_r(str_deletions ($str));
output for above function call is
Array ( [output] => abc [deletions] => 4 )
Solved with no external function except count;
$str="aaavvvffccca";
$count = strlen($str);
for($i=0;$i<$count;$i++){
$array[]=$str[$i];
}
$del =0;
for($i=0;$i<$count;$i++){
$next=isset($array[$i+1])?$array[$i+1]:null;
if($array[$i]==$next)
{
$del++;
}
else
{
$newarray[]=$array[$i];
}
}
echo "Filter Text:". implode('',$newarray);
echo"Total Deleted:".$del;
The straight forward solution to find out the number of deletions can be
If there are N consecutive same characters delete N-1 out of those N characters.
function str_likes($str)
{
$length = strlen($str);
$del = 0;
for ($i=0 ; $i < $length ; $i++)
{
if ($str[$i] == $str[$i+1])
{
$del++;
}
}
return $del;
}
$str = "aabbccaaa";
echo str_likes($str); //4
Is there a way to trim a text string in PHP so it has a certain number of characters? For instance, if I had the string:
$string = "this is a string";
How could I trim it to say:
$newstring = "this is";
This is what I have so far, using chunk_split(), but it isn't working. Can anyone improve on my method?
function trimtext($text)
{
$newtext = chunk_split($text,15);
return $newtext;
}
I also looked at this question, but I don't really understand it.
if (strlen($yourString) > 15) // if you want...
{
$maxLength = 14;
$yourString = substr($yourString, 0, $maxLength);
}
will do the job.
Take a look here.
substr cuts words in half. Also if word contains UTF8 characters, it misbehaves. So it would be better to use mb_substr:
$string = mb_substr('word word word word', 0, 10, 'utf8').'...';
You didn't say the reason for this but think about what you want to achieve. Here is a function for shorten a string word by word with or without adding ellipses at the end:
function limitStrlen($input, $length, $ellipses = true, $strip_html = true) {
//strip tags, if desired
if ($strip_html) {
$input = strip_tags($input);
}
//no need to trim, already shorter than trim length
if (strlen($input) <= $length) {
return $input;
}
//find last space within length
$last_space = strrpos(substr($input, 0, $length), ' ');
if($last_space !== false) {
$trimmed_text = substr($input, 0, $last_space);
} else {
$trimmed_text = substr($input, 0, $length);
}
//add ellipses (...)
if ($ellipses) {
$trimmed_text .= '...';
}
return $trimmed_text;
}
function trimtext($text, $start, $len)
{
return substr($text, $start, $len);
}
You can call the function like this:
$string = trimtext("this is a string", 0, 10);
Would return:
This is a
substr let's you take a portion of string consisting of exactly as much characters as you need.
You can use this
substr()
function to get substring
If you want to get a string with a certain number of characters you can use substr, i.e.
$newtext = substr($string,0,$length);
where $length is the given length of the new string.
If you want an abstract for the first 10 words (you can use html in $text, before script there is strip_tags)
use this code:
preg_match('/^([^.!?\s]*[\.!?\s]+){0,10}/', strip_tags($text), $abstract);
echo $abstract[0];
My function has some length to it, but I like to use it. I convert the string int to a Array.
function truncate($text, $limit){
//Set Up
$array = [];
$count = -1;
//Turning String into an Array
$split_text = explode(" ", $text);
//Loop for the length of words you want
while($count < $limit - 1){
$count++;
$array[] = $split_text[$count];
}
//Converting Array back into a String
$text = implode(" ", $array);
return $text." ...";
}
Or if the text is coming from an editor and you want to strip out the HTML tags.
function truncate($text, $limit){
//Set Up
$array = [];
$count = -1;
$text = filter_var($text, FILTER_SANITIZE_STRING);
//Turning String into an Array
$split_text = preg_split('/\s+/', $text);
//Loop for the length of words you want
while($count < $limit){
$count++;
$array[] = $split_text[$count];
}
//Converting Array back into a String
$text = implode(" ", $array);
return $text." ...";
}
With elipsis (...) only if longer - and taking care of special language-specific characters:
mb_strlen($text,'UTF-8') > 60 ? mb_substr($text, 0, 60,'UTF-8') . "…" : $text;
I have a string like this:
$string = "1,4|2,64|3,0|4,18|";
Which is the easiest way to access a number after a comma?
For example, if I have:
$whichOne = 2;
If whichOne is equal to 2, then I want to put 64 in a string, and add a number to it, and then put it back again where it belongs (next to 2,)
Hope you understand!
genesis'es answer with modification
$search_for = 2;
$pairs = explode("|", $string);
foreach ($pairs as $index=>$pair)
{
$numbers = explode(',',$pair);
if ($numbers[0] == $search_for){
//do whatever you want here
//for example:
$numbers[1] += 100; // 100 + 64 = 164
$pairs[index] = implode(',',$numbers); //push them back
break;
}
}
$new_string = implode('|',$pairs);
$numbers = explode("|", $string);
foreach ($numbers as $number)
{
$int[] = intval($number);
}
print_r($int);
$string = "1,4|2,64|3,0|4,18|";
$coordinates = explode('|', $string);
foreach ($coordinates as $v) {
if ($v) {
$ex = explode(',', $v);
$values[$ex[0]] = $ex[1];
}
}
To find the value of say, 2, you can use $whichOne = $values[2];, which is 64
I think it is much better to use the foreach like everyone else has suggested, but you could do it like the below:
$string = "1,4|2,64|3,0|4,18|";
$whichOne = "2";
echo "Starting String: $string <br>";
$pos = strpos($string, $whichOne);
//Accomodates for the number 2 and the comma
$valuepos = substr($string, $pos + 2);
$tempstring = explode("|", $valuepos);
$value = $tempstring[0]; //This will ow be 64
$newValue = $value + 18;
//Ensures you only replace the index of 2, not any other values of 64
$replaceValue = "|".$whichOne.",".$value;
$newValue = "|".$whichOne.",".$newValue;
$string = str_replace($replaceValue, $newValue, $string);
echo "Ending String: $string";
This results in:
Starting String: 1,4|2,64|3,0|4,18|
Ending String: 1,4|2,82|3,0|4,18|
You could run into issues if there is more than one index of 2... this will only work with the first instance of 2.
Hope this helps!
I know this question is already answered, but I did one-line solution (and maybe it's faster, too):
$string = "1,4|2,64|3,0|4,18|";
$whichOne = 2;
$increment = 100;
echo preg_replace("/({$whichOne},)(\d+)/e", "'\\1'.(\\2+$increment)", $string);
Example run in a console:
noice-macbook:~/temp% php 6642400.php
1,4|2,164|3,0|4,18|
See http://us.php.net/manual/en/function.preg-replace.php