php: split string into 3 parts by two delimiters where the first and the last “delimiters” are letters or numbers respectively

旧时模样 提交于 2019-12-23 02:58:18

问题


Any ideas how to split string into 3 parts where by two "delimiters" where the first and the last "delimiters" are letters or numbers respectively?

$str = "%@-H-e-l-l-o-7-9#$%";

would be split like this:

$arr=("%@-","H-e-l-l-o-7-9", "#$%");

and

$str = "Hi$73";

would be split like this:

$arr=("","Hi$73", "");

and

$str = "Беларусь!";

would be split like this:

$arr=("","Беларусь", "!");

and

$str = "!";

would be split like this:

$arr=("!","", "");

and

$str = "";

would be split like this:

$arr=("","", "");

and

$str = "ў55ЎW";

would be split like this:

$arr=("","ў55ЎW", "");

which means it returns an array that consists of 3 elements (always), and the first and last symbols of the second element are numbers or latin/cyrillic letters, and the first and last(third) elements of this array contain absolutely no numbers and letters, and the join of that strings is the source string

Thank you.


回答1:


Here is a way to do the job:

$in = array(
"%@-H-e-l-l-o-7-9#$%",
"Hi$73",
"Беларусь!",
"!",
"",
"ў55ЎW",
'$abc$$$',
"асоба_",
"34.5",
'#_!',
);

foreach($in as $elem) {
    preg_match('/^([^\pL\pN]*)((?=[\pL\pN]|$)[^_]*(?<=[\pL\pN])|^)?([^\pL\pN]*)$/u', $elem, $m);
    printf("'%15s'%s'%10s'\t%s'%10s'\t%s'%10s'%s", "$elem","=> (1): ",$m[1],"(2): ",$m[2], "(3): ",$m[3],"\n");

}

Where:

  • \pL stands for any letter in any language
  • \pN stands for any number in any language

Output:

'%@-H-e-l-l-o-7-9#$%'=> (1): '       %@-'   (2): 'H-e-l-l-o-7-9'    (3): '       #$%'
'          Hi$73'=> (1): '          '   (2): '     Hi$73'   (3): '          '
'Беларусь!'=> (1): '          ' (2): 'Беларусь' (3): '         !'
'              !'=> (1): '         !'   (2): '          '   (3): '          '
'               '=> (1): '          '   (2): '          '   (3): '          '
'        ў55ЎW'=> (1): '          ' (2): '   ў55ЎW' (3): '          '
'        $abc$$$'=> (1): '         $'   (2): '       abc'   (3): '       $$$'
'    асоба_'=> (1): '          '    (2): 'асоба'    (3): '         _'
'           34.5'=> (1): '          '   (2): '      34.5'   (3): '          '
'            #_!'=> (1): '       #_!'   (2): '          '   (3): '          '



回答2:


The solution using preg_match and array_slice functions:

$str = "%@-H-e-l-l-o-7-9#$%";

preg_match('/^([^\w]*)(\w+.*\w+|\w)?([^\w]*)$/iu', $str, $matches);
$parts = array_slice($matches, 1);

print_r($parts);

The output:

Array
(
    [0] => %@-
    [1] => H-e-l-l-o-7-9
    [2] => #$%
)

This approach will work for all of your presented input cases



来源:https://stackoverflow.com/questions/41910966/php-split-string-into-3-parts-by-two-delimiters-where-the-first-and-the-last-d

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