How to explode a string by any integer? Regex?

故事扮演 提交于 2019-12-01 08:30:01

You should use the PREG_SPLIT_DELIM_CAPTURE flag to capture the group which you made the split on. Here's an example:

<?php

$key= "group12";
$pattern = "/(\d+)/";

$array = preg_split($pattern, $key, -1, PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE);
print_r($array);

?>

Note that you combine several flags using the | "bitwise or" operator.

Output:

Array
(
    [0] => group
    [1] => 12
)

Try this one:

/(\D+)(\d+)/

PHP example code:

<?php
$str = 'test189';
$pattern = '/(\D+)(\d+)/';

$res = preg_match_all($pattern, $str, $matches);
var_dump($matches);

?>

Use preg_match with capturing parentheses:

<?php

$str = "type10";

$matches = array();

preg_match('/([a-zA-Z]+)(\d+)/', $str, $matches );

print_r($matches);

?>

Outputs:

Array(
    0 => "type10"
    1 => "type"
    2 => "10"
)

Then, to get rid of the first element:

<?php
array_shift($matches);
print_r($matches);
?>

To give:

Array(
    0 => "type"
    1 => "10"
)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!