Separating a String without defined delimiter

Asked

Viewed 189 times

-1

I need some help, I have a String ex: 95YAH0T01MJ456348 - this String will always contain 17 digits and the String must always be separated in the first 6 digits so you can pick up and make a comparison in the database to identify the model. However I did not find any function that makes this separation, neither in PHP nor SQL (MYSQL).

  • 3

    https://www.php.net/manual/en/function.substr.php

  • I got it with your comment, super simple, thank you!

  • Just to be clear: your string (95YAH0T01MJ456348) contains 17 characters but only 11 digits. Maybe you are confusing the nomenclature. If it can contain a mixture of characters and you want to consider only 6 digits the position where separate can vary. Define clearly and precisely your problem.

1 answer

3

As stated in the comments use the function substr() to return a part of a string.

This function has the following signature:

substr ( string $string , int $start [, int $length ] ) : string

Where:

  • $string: It is the string whose part must be returned.
  • $start : It is the index where the substring part begins to be returned.
  • $length: It is the length of substring to be returned.

In the manual of substr() there are other important considerations regarding the parameters $start and $length.

Example:

<?php

$s = "95YAH0T01MJ456348";

//O primeiro elemento, onde o índice é zero, são os seis primeiros caracteres de $s 
//o segundo elemento, cujo índice é um, são os caracteres remanescentes.
$res = [substr($s, 0, 6), substr($s, 6)];

print_r($res);

?>

Resulting:

Array
(
    [0] => 95YAH0
    [1] => T01MJ456348
)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.