正则表达式 - 将“//”替换为“”

时间:2013-07-03 07:03:18

标签: php regex

RegEx for PhoneNumbers有些麻烦,它到目前为止工作但我无法弄清楚如何用空格补充“//”:

输入:0()()()111 1-11 * // * 1111

预期 :: +49 111 111 1111

得到:+49 111 1111111

$pattern = array(
            '/[^0-9\+\.\-\(\) ]/',   // Cut all characters that are not allowed
            '/^00/',                 // Start with 00 ist changed to +
            '/^(0)(\d)/',            // Start with 0[1-9] ist changed to +49 [0-9]
            '/[\.\-\(\)]/',          // Change allowed characters to ' '
            '/\s[\s]+/',             // Change grouped spaces too one
            '/((\+49 )(0))(.*)/'
        );

$change = array('', '+', '+49 $2', ' ', ' ', '$2$4');
$value = preg_replace($pattern, $change, $value);

将Chars添加到:

 '/[\.\-\(\)]/',          // Change allowed characters to ' '

哪个不起作用。对不起,我对Regex的了解有限。

2 个答案:

答案 0 :(得分:1)

试试这个,我刚试过它并且有效。所以首先我要替换双斜杠,然后替换不允许的字符。

$pattern = array(
            '/[\/]{2}/',             // Replacing //
            '/[^0-9\+\.\-\(\) ]/',   // Cut all characters that are not allowed
            '/^00/',                 // Start with 00 ist changed to +
            '/^(0)(\d)/',            // Start with 0[1-9] ist changed to +49 [0-9]
            '/[\.\-\(\)]/',          // Change allowed characters to ' '
            '/\s[\s]+/',             // Change grouped spaces too one
            '/((\+49 )(0))(.*)/'
        );

$change = array(' ', '', '+', '+49 $2', ' ', ' ', '$2$4');
$value = preg_replace($pattern, $change, $value);

答案 1 :(得分:1)

我无法找到将*//*替换为空格的模式!有两个模式替换为第3和第4空间,其中第3 '/[\.\-\(\)]/'仅针对以下字符{{1和你说的白色空间的第4个。

另一点是第一个模式是在其他人看到它们之前删除它们,因为列表中有.-()*以及不允许的字符,

所以在第一个模式之后你将拥有以下字符串/ 它将继续执行其他模式。