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
Related
$beforeDot = explode(".", $string)[0];
This is what I'm attempting to do, except that it returns syntax error. If there is a workaround for a one liner, please let me know. If this is not possible, please explain.
The function array dereferencing was implemented in PHP 5.4, so if you are using an older version you'll have to do it another way.
Here's a simple way to do it:
$beforeDot = array_shift(explode('.', $string));
You can use list for this:
list($first) = explode(".", "foo.bar");
echo $first; // foo
This also works if you need the second (or third, etc.) element:
list($_, $second) = explode(".", "foo.bar");
echo $second; // bar
But that can get pretty clumsy.
Use current(), to get first position after explode:
$beforeDot = current(explode(".", $string));
Use array_shift() for this purpose :
$beforeDot = array_shift(explode(".", $string));
in php <= 5.3 you need to use
$beforeDot = explode(".", $string);
$beforeDot = $beforeDot[0];
2020 : Google brought me here for something similar.
Pairing 'explode' with 'implode' to populate a variable.
explode -> break the string into an array at the separator
implode -> get a string from that first array element into a variable
$str = "ABC.66778899";
$first = implode(explode('.', $str, -1));
Will give you 'ABC' as a string.
Adjust the limit argument in explode as per your string characteristics.
You can use the limit parameter in the explode function
explode($separator, $str, $limit)
$txt = 'the quick brown fox';
$explode = explode(' ', $txt, -substr_count($txt, ' '));
This will return an array with only one index that has the first word which is "the"
PHP Explode docs
Explanation:
If the limit parameter is negative, all components except the last
-limit are returned.
So to get only the first element despite the number of occurences of the substr you use -substr_count
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];
I have strings:
17s 283ms
48s 968ms
The string values are never the same and I want to extract the "second" value from it. In this case, the 17 and the 48.
I'm not very good with regex, so the workaround I did was this:
$str = "17s 283ms";
$split_str = explode(' ', $str);
foreach($split_str as $val){
if(strpos($val, 's') !== false) $sec = intval($val);
}
The problem is, the character 's' exists in both split_str[0] and split_str[1], so my $sec variable keeps obtaining 283, instead of 17.
Again, I'm not very good with regex, and I'm pretty sure regex is the way to go in this case. Please assist. Thanks.
You don't even need to use regex for this.
$seconds = substr($str, 0, strspn($str, '1234567890'));
The above solution will extract all the digits from the beginning of the string. Doesn't matter if the first non-digit character is "s", a space, or anything else.
But why bother?
You can even just cast $str to an int:
$seconds = (int)$str; // equivalent: intval($str)
See it in action.
Regular expressions are definite overkill for such a simple task. Don't use dynamite to drill holes in the wall.
You could do this like so:
preg_match('/(?<seconds>\d+)s\s*(?<milliseconds>\d+)ms/', $var, $matches);
print_r($matches);
If the string will always be formatted in this manner, you could simply use:
<?php
$timeString = '17s 283ms';
$seconds = substr($timeString, 0, strpos($timeString, 's'));
?>
Well, i guess that you can assume seconds always comes before milliseconds. No need for regexp if the format is consistent. This should do it:
$parts = explode(' ', $str);
$seconds = rtrim($parts[0], 's')
echo $seconds; // 17s
This will split the string by space and take the first part 17s. rtrim is then used to remove 's' and you're left with 17.
(\d+s) \d+ms
is the right regexp. Usage would be something like this:
$str = "17s 283ms";
$groups = array();
preg_match("/(\d+)s \d+ms/", $str, $groups);
Then, your number before ms would be $groups[1].
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
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!!!