Home > Mobile >  how to truncate dinamic string in php?
how to truncate dinamic string in php?

Time:07-31

I have dynamic array data which has different code :

[0] 18572834-2.2.2.4
[1] 185-2.1

here i want to fetch data after ( - ) dynamically, may I know what function to use in php ?

output

[0] 2.2.2.4
[1] 2.1

CodePudding user response:

foreach, array_map, explode you should know the drill.

$arr = ["18572834-2.2.2.4", "185-2.1"];
$result = array_map(function($item) {
  return explode("-", $item, 2)[1];
}, $arr);

CodePudding user response:

If I understood the question I think you can first implode the array to get a string and then explode the array using "-" as separator.

$arr = implode("", $arr);
$splitted = explode("-", $arr)

Then you have an array with "185" at index 0 and "2.1" at index 1 so you just take the index 1.

So:

$splitted[0x1] = 2.1

But Explode will divide the string in pieces for every delimitator, so if you have: 123-456-789 you will get an array

$arr[0] = 123 
$arr[1] = 456 
$arr[2] = 789

And I don't know if it is what you want. If you want to take the numbers only from the first delimiter (so 456-789) you can use a regular expression or split and then rejoin the array or do a substring from the position of the delimiter

  • Related