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!
4 Answers
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));
7 Comments
Jelle Ferwerda
Not sure that would work. Explode takes the delimiter first, afaik ..?
Alma Do
That's all about mess with implode/explode .. thank you (first one accepts args in any order)
Darsstar
If the input can contain more then one dash use end() instead of hardcoding it to the second part.
Alma Do
@Darsstar fair enough. But
end() is not needed since array_pop() existsHammad
@AlmaDoMundo Thank you very much for your answer as it handles the possible scenario of - occuring more than once.
|
-are your best tool for the job? what if you get a string like3 kit-kat tablets-12.00? have you ever heard of JSON?json_encode()andjson_decode(). Also, the very fact that the user has to manually type3 kit-kat tablets-12.00is a bad design. You need to have 3 different input fields (quantity, product and price) and then send them through a form. HTTP then will properly handle the transmission of these values and you won't need to do any string manipulation.