PHP:如何通过正则表达式获取子字符串

时间:2012-10-31 12:52:11

标签: php regex

我有像这样的htaccess规则:

RewriteRule ^([A-z])([0-9]+)-([^/]*)?$ index.php?tt=$1&ii=$2&ll=$3

是否有任何PHP功能可以做同样的事情? 类似的东西:

$A = XXXX_preg_match("([A-z])([0-9]+)-([^/]*)" , "A123-boooooo");
// $A become to =array("A","123","boooooo")

3 个答案:

答案 0 :(得分:1)

如果您只想检索这三个值,可以将out参数传递给preg_match,如下所示:

preg_match(
    '~^([A-z])([0-9]+)-([^/]*)$~' ,
    'A123-boooooo',
    $matches
);

$fullMatch = $matches[0]; // 'A123-boooooo'
$letter = $matches[1];    // 'A'
$number = $matches[2];    // '123'
$word = $matches[3];      // 'boooooo'

// Therefore
$A = array_slice($matches, 1);

如果您想立即进行更换,请使用preg_replace

$newString = preg_replace(
    '~^([A-z])([0-9]+)-([^/]*)$~',
    'index.php?tt=$1&ii=$2&ll=$3',
    'A123-boooooo
);

这些documentation通常非常适合获取更多信息。

答案 1 :(得分:1)

preg_match('/([a-zA-Z])(\d+)-([^\/]+)/', 'A123-boooooo', $A);
array_shift($A);

输出: print_r($A);

Array
(
    [0] => A
    [1] => 123
    [2] => boooooo
)

答案 2 :(得分:0)

根据preg_match doc

preg_match("~([A-z])([0-9]+)-([^/]*)~" , "A123-boooooo", $matches);
print_r($matches);

<强>输出:

Array
(
    [0] => A123-boooooo
    [1] => A
    [2] => 123
    [3] => boooooo
)