正则表达式匹配位置

时间:2016-09-04 18:05:48

标签: php regex

$str1 = '10 sold';

$re = "/(?<Alpha>[a-zA-Z]*)(?<Numeric>[0-9]*)/";       
preg_match_all($re, $str1, $str1matches);

echo print_r($str1matches,1);

打印:

Array

(
    [0] => Array
        (
            [0] => 10
            [1] => 
            [2] => sold
            [3] => 
        )

    [Alpha] => Array
        (
            [0] => 
            [1] => 
            [2] => sold
            [3] => 
        )

    [1] => Array
        (
            [0] => 
            [1] => 
            [2] => sold
            [3] => 
        )

    [Numeric] => Array
        (
            [0] => 10
            [1] => 
            [2] => 
            [3] => 
        )

    [2] => Array
        (
            [0] => 10
            [1] => 
            [2] => 
            [3] => 
        )

)

但是为什么要打印这么长的数组呢?如何确定我的值(xxxlabel)始终可用于哪个位置?

1 个答案:

答案 0 :(得分:1)

我使用简单的/^([0-9]+)\s*([a-zA-Z]+)$/正则表达式,因为you confirm输入字符串中有一个数字,然后是一个单词:

preg_match('/^([0-9]+)\s*([a-zA-Z]+)$/', '10 sold', $str1matches, PREG_OFFSET_CAPTURE);

请参阅PHP demo

$str1 = '10 sold';
$re = "/^([0-9]+)\s*([a-zA-Z]+)$/";       
preg_match($re, $str1, $str1matches, PREG_OFFSET_CAPTURE);
echo print_r($str1matches[1]);
echo print_r($str1matches[2]);

$str1matches[1]将包含一个包含Group 1(数字)值及其位置的数组,$str1matches[2]将包含一个包含Group 2(word)值及其位置的数组。