How to split line based on position

I want to split a variable based on character position. As a result, the first line should have the previous position before the specified position, and the other line should contain other parts.

Suppose if I have a variable $var = "2013AD";I want

$var1 = 2013and var2 = 'AD'.

How can i achieve this?

-1
source share
4 answers

Uh ... I'll go here, there is a razor, but substr ?

$var1 = substr($var, 0, 4);
$var2 = substr($var, 4);
+7
source

You can just use sscanf

$var = "2013AD";
list($var1, $var2) = sscanf($var, "%4d%2s");
echo $var1, ":", $var2;

Exit

2013:AD

And if you work with date, consider it as such:

$var = "2013AD";
$date  = DateTime::createFromFormat("Y\A\D",$var);
echo $date->format("Y");
+3
source
<?php

function py_slice($input, $slice) {
    $arg = explode(':', $slice);
    $start = intval($arg[0]);
    if ($start < 0) {
        $start += strlen($input);
    }
    if (count($arg) === 1) {
        return substr($input, $start, 1);
    }
    if (trim($arg[1]) === '') {
        return substr($input, $start);
    }
    $end = intval($arg[1]);
    if ($end < 0) {
        $end += strlen($input);
    }
    return substr($input, $start, $end - $start);
}

print py_slice('abcdefg', '2') . "\n";
print py_slice('abcdefg', '2:4') . "\n";
print py_slice('abcdefg', '2:') . "\n";
print py_slice('abcdefg', ':4') . "\n";
print py_slice('abcdefg', ':-3') . "\n";
print py_slice('abcdefg', '-3:') . "\n";

?>

:

  • c
  • cd
  • cdefg
  • ABCD
  • ABCD
  • EFG
+1

substr

$var1 = substr($var, 0, 4);
$var2 = substr($var, 4);
0

Source: https://habr.com/ru/post/1612033/


All Articles