Increment integer at end of string - php

I have a string, "Chicago-Illinos1" and I want to add one to the end of it, so it would be "Chicago-Illinos2".
Note: it could also be Chicago-Illinos10 and I want it to go to Chicago-Illinos11 so I can't do substr.
Any suggested solutions?

Complex solutions for a really simple problem...
$str = 'Chicago-Illinos1';
echo $str++; //Chicago-Illinos2
If the string ends with a number, it will increment the number (eg: 'abc123'++ = 'abc124').
If the string ends with a letter, the letter will be incremeted (eg: '123abc'++ = '123abd')

Try this
preg_match("/(.*?)(\d+)$/","Chicago-Illinos1",$matches);
$newstring = $matches[1].($matches[2]+1);
(can't try it now but it should work)

$string = 'Chicago-Illinois1';
preg_match('/^([^\d]+)([\d]*?)$/', $string, $match);
$string = $match[1];
$number = $match[2] + 1;
$string .= $number;
Tested, works.

explode could do the job aswell
<?php
$str="Chicago-Illinos1"; //our original string
$temp=explode("Chicago-Illinos",$str); //making an array of it
$str="Chicago-Illinos".($temp[1]+1); //the text and the number+1
?>

I would use a regular expression to get the number at the end of a string (for Java it would be [0-9]+$), increase it (int number = Integer.parse(yourNumberAsString) + 1), and concatenate with Chicago-Illinos (the rest not matched by the regular expression used for finding the number).

You can use preg_match to accomplish this:
$name = 'Chicago-Illinos10';
preg_match('/(.*?)(\d+)$/', $name, $match);
$base = $match[1];
$num = $match[2]+1;
print $base.$num;
The following will output:
Chicago-Illinos11
However, if it's possible, I'd suggest placing another delimiting character between the text and number. For example, if you placed a pipe, you could simply do an explode and grab the second part of the array. It would be much simpler.
$name = 'Chicago-Illinos|1';
$parts = explode('|', $name);
print $parts[0].($parts[1]+1);
If string length is a concern (thus the misspelling of Illinois), you could switch to the state abbreviations. (i.e. Chicago-IL|1)

$str = 'Chicago-Illinos1';
echo ++$str;
http://php.net/manual/en/language.operators.increment.php

Related

Get all numeric before first Alpha in PHP String

I'm trying to get all numeric before space/alpha in PHP string.
Example:
<?php
//string
$firstStr = '12 Car';
$secondStr = '412 8all';
$thirdStr = '100Pen';
//result I need
firstStr = 12
SecondStr = 412
thirdStr = 100
How do I can get all the number of a string just like example above?
I've an idea to get the position of first Alpha, then get all numeric before that position.
I've successfully get the position using
preg_match('~[a-z]~i', $value, $match, PREG_OFFSET_CAPTURE);
But I'm not done yet to get the numeric before the posisition.
How do I can do that, or anybody know how to fix my idea?
Anyhelp will be appreciated.
You don't need to use regex for strings like the examples you've shown, or any functions at all for that matter. You can just cast them to ints.
$number = (int) $firstStr; // etc.
The PHP rules for string conversion to number will handle it for you.
However, because of those rules, there are some other types of strings that this won't work for. For example, '-12 Car' or '412e2 8all'.
If you do use a regex, be sure to anchor it to the beginning of the string with ^ or it will match digits anywhere in the string as the other regex answers here do.
preg_match('/^\d+/', $string, $match);
$number = $match[0] ?? '';
Here's an extremely hackish approach that will work in most situations:
$s = "1001BigHairyCamels";
$n = intval($s);
$my_number = str_replace($n, '', $s);
$input = '100Pen';
if (preg_match('~(\d+)[ a-zA-Z]~', $input, $m)) {
echo $m[1];
}
This function will do the job!
<?php
function getInt($str){
preg_match_all('!\d+!', $str, $matches);
return $matches[0][0];
}
$firstStr = '12 Car';
$secondStr = '412 8all';
$thirdStr = '100Pen';
echo 'firstStr = '.getInt($firstStr).'<br>';
echo 'secondStr = '.getInt($secondStr).'<br>';
echo 'thirdStr = '.getInt($thirdStr);
?>

Adding something to the start of a variable?

I am looking for some code that allows you to add +44 onto the beginning of my $string variable.
So the ending product would be:
$string = 071111111111
+44071111111111
Your $string variable isn't actually a string in this scenario; it's an integer. Make it a string by putting quotes around it:
$string = "071111111111"
Then you can use the . operator to append one string to another, so you could do this:
$string = "+44" . $string
Now $string is +44071111111111. You can read more about how to use the . (string concatenation operator) on the PHP documentation here.
Other people's suggestions of just keeping $string as an integer wouldn't work: "+44" . 071111111111 is actually +447669584457. Due to the 0 at the start of the number, PHP converts it to an octal number rather than a decimal one.
You can combine strings by .
$string = '+44'.$string;
You can use universal code, which works with another parameters too.
<?php
$code = "+44";
$string = "071111111111";
function prepend(& $string, $code) {
$test = substr_replace($string, $code, 0, 0);
echo $test;
}
prepend($string, $code);
?>

Get the last value in a comma-separated string

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

How to get part of string from the end in PHP?

I am making application where I receive a string from user. The string is concatenated with - character between them. First part of string contains alphabetic data whereas later part contains integers or floating point numbers. For example: A string might be 3 Cups Tea-5.99.I want to get the later part of string 5.99 separated by - character. How to do that? I know about PHP substr() function but that takes fixed characters to retrieve substring from. But in this case the later part will not be fixed. For example: 2 Jeans-65.99. In this case I would need last 4 characters meaning that I can't use substr() function.
Anybody with solution?
I know I would need to apply regex but I am completely novice in Regex.
Waiting for your help.
Thanks!
Simply
$result = explode('-', $string)[1];
For PHP<5.4 you'll have to use temporary variable:
$data = explode('-', $string);
$result = $data[1];
Edit
As mentioned in comments, if there is more than 1 part, that will be:
$result = array_pop(explode('-', $string));
$bits = explode('-', $inputstring);
echo $bits[1];
You can use substr() with strpos():
$str = '3 Cups Tea-5.99';
echo substr($str, strpos($str, "-") + 1);
Output:
5.99
Demo!
If data will be like this: "1-Cup tea-2.99", then
$data = "1-Cup tea-2.99";
$data = explode('-', $string);
$result = $data[count($data)-1];

How can we split a sentence

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!!!

Categories