Home > OS >  PHP separate two strings
PHP separate two strings

Time:12-01

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

CodePudding user response:

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

CodePudding user response:

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

CodePudding user response:

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.

CodePudding user response:

Use https://www.php.net/manual/en/function.explode.php

$string = "ACCESS_NUMBER:160375356:13176570247";
$stringOne = explode(':', $string)[1];
$stringTwo = explode(':', $string)[2];
  •  Tags:  
  • php
  • Related