Home > Blockchain >  Split Parts only if second part starst with specific char
Split Parts only if second part starst with specific char

Time:08-27

I have string set like the following example;

"Some string without integer 12345a1% rest of the string with/without integer"

After extracting 12345a1% from the actual string I want to split extracted string by two part; the first part is the number part, and the second part is the first character and rest of the numbers. But the second part should only be split if the starting character is specific (a,d,m,n,o).

Example;

// First
"Some string 12345a1% some other string."

// Second
"Somet string 23456b2! some other string

Desired output;

// First
0 => 12345
1 => "a1"

// Second
0 => 23456
1 => null

What I tried is the following but I get incorrect result.

$split = preg_split('/\$([0-9]*)(a|d|m|n|o\s)(\d*)/', $input, -1, PREG_SPLIT_NO_EMPTY);

Is there any point am I missing? Thanks in advance.

CodePudding user response:

Taking the Some string without integer part into account, you can match starting from the first digits, and then optionally match any of [admno] followed by 1 or more digits.

That will only give you the capture 2 value if it exists instead of null.

^[^\d\r\n]*\b(\d )([admno]\d )?

Explanation

  • ^ Start of string
  • [^\d\r\n]* Optionally match any char except a newline or digit
  • \b A word boundary to prevent a partial word match
  • (\d ) Capture group 1, match 1 digits
  • ([admno]\d )? Optional capture group 2, match one of [admno] and 1 digits

See a regex demo and a PHP demo.

For example using preg_match instead of preg_split (where the first entry is the full match):

$pattern = '/^[^\d\r\n]*\b(\d )([admno]\d )?/';
$strings = [
    "Some string 12345a1% some other string.",
    "Somet string 23456b2! some other string"
];

foreach ($strings as $s) {
    preg_match($pattern, $s, $match);
    var_dump($match);
}

Output

array(3) {
  [0]=>
  string(19) "Some string 12345a1"
  [1]=>
  string(5) "12345"
  [2]=>
  string(2) "a1"
}
array(2) {
  [0]=>
  string(18) "Somet string 23456"
  [1]=>
  string(5) "23456"
}
  • Related