skip to Main Content

I need a code to get the first and second numbers from the PHP string.

$string = "ACCESS_NUMBER:160375356:13176570247"; $stringOne = ""; $stringTwo = "";
I need a code that can get 160375356 and store it in $stringOne and also get this 13176570247 and store it in string $stringTwo

I don’t want to count the strings, I need a code that can get them via this: sign

3

Answers


  1. This example should help

    $pizza  = "piece1 piece2 piece3 piece4 piece5 piece6";
    $pieces = explode(" ", $pizza);
    echo $pieces[0]; // piece1
    echo $pieces[1]; // piece2
    

    You can use the explode() function to explode a String into an array
    Change it to fit your needs

    Login or Signup to reply.
  2. You can achieve it with

    <?php 
    $string = "ACCESS_NUMBER:160375356:13176570247";
    $parts = explode(':', $string);
    $stringOne = $parts[1];
    $stringTwo = $parts[2];
    ?>
    

    And if that is not sufficient other solution would be to use regex, but regex solution is heavier.

    explode function takes two parameters – delimeter and string. Then it traverse through string until it finds delimiter. After finding delimiter it puts part of string in result array – from last delimiter (or beginning) till this delimiter, omiting the delimiter. Then travers more until reaches end of string – and this is the last time it puts part of string in result array.

    For example for

    explode('#', 'Apple#Banana#Orange')
    

    We will get array with three elements "Apple", "Banana" and "Orange" – we can access them with array index.

    Regex solution is heavier because every regex is in fact a finite state machine. It also traverse throught string but do different kind of operations – can do more complex matches. But it also means it requires more memory and processor power to do computations.

    Basically idea is that if you can achieve something with explode, substring etc. then go with it, if you cannot or you can but it will require complex code then go with regex.

    Login or Signup to reply.
  3. Lots of answers here already, but not a real clean one. How about:

    <?php 
    $string = "ACCESS_NUMBER:160375356:13176570247";
    [, $stringOne, $stringTwo] = explode(':', $string);
    

    See: https://3v4l.org/GjOUH

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search