正则表达式显示错误

时间:2015-01-19 05:36:05

标签: php regex

这是我的代码:

<?php

$userinfo = "Scandinavia:\Swiden\Norwaya\Finland\Denmark\Iceland";


$userinfo = addslashes($userinfo);

// preg_match_all ("/(.*\\)/U", $userinfo, $pat_array);

preg_match_all ("/(.*\)/U", $userinfo, $pat_array);

print_r($pat_array);
?>

我想要匹配“斯堪的纳维亚:”,“瑞典”...... 请帮我纠正这段代码。

2 个答案:

答案 0 :(得分:3)

在\之前使用\\ 解决方案:

<?php
$userinfo = 'Scandinavia:\Swiden\Norwaya\Finland\Denmark\Iceland';
$userinfo = addslashes($userinfo);
preg_match_all ("/(.*\\\)/U", $userinfo, $pat_array);
print_r($pat_array);
?>

答案 1 :(得分:0)

将以下正则表达式与preg_match_all

一起使用
'~[^\\\\]+\\\\~'

[^\\\\]+匹配任何字符,但不匹配反斜杠字符一次或多次。

DEMO

$userinfo = "Scandinavia:\Swiden\Norwaya\Finland\Denmark\Iceland";
$userinfo = addslashes($userinfo);
preg_match_all ('~[^\\\\]+\\\\~', $userinfo, $pat_array);
print_r($pat_array);

输出:

Array
(
    [0] => Array
        (
            [0] => Scandinavia:\
            [1] => Swiden\
            [2] => Norwaya\
            [3] => Finland\
            [4] => Denmark\
        )

)