php Regex在一个角色之前和另一个角色之前

时间:2017-05-15 12:00:07

标签: php regex

我有一个清单:

firstname.lastname (location)

我想提取名字,姓氏和位置。它可以是位置中的点,但它总是在括号之间。

有人能帮帮我吗? (如果可能的话,给出正则表达式的解释,我不知道为什么我永远不能创建自己的正则表达式...)

我找到了:

#\((.*?)\)# for the location
^[^\.]+ for the firstname

但是我找不到姓氏,我也不知道如何将所有3个匹配在一起

4 个答案:

答案 0 :(得分:0)

你可以在没有正则表达式的情况下完成:

$string = 'firstname.lastname (location)';
//you get there array of name and surname
$exploded = explode('.',substr($string, 0, strpos($string, ' ')));

$name = $exploded[0];
$surname = $exploded[1];
//You get there location
$location = rtrim(explode(' (', $string)[1], ')');

答案 1 :(得分:0)

你不需要正则表达式。 .上的explode(),限制为2.然后strpos()第一个括号(substr()完成剩下的工作。

答案 2 :(得分:0)

正则表达式并不太难。但是,您的混淆可能源于该示例字符串中的几个字符在RegEx中具有特殊含义。

<?php
    $string = "firstname.lastname (location)";

    if(preg_match('/^(\w+)\.(\w+)\s*\((\w*)\)$/', $string, $aCapture)){

    /*Let's break down that regex

     ^       Start of string
     (\w+)   Capture a string of continuous characters
     \.      a period
     (\w+)   Capture a string of continuous characters
     \s      Zero or more whitespace
     \(      An opening bracket
     (\w+)   Capture a string of continuous characters
     \)      An closing bracket
     $       The end of the string

     */

        $aCapture contains your captures; starting at position 1, because 0 will contain the entire string
        $sFirstName = $aCapture[1];
        $sLastName = $aCapture[2];
        $sLocation = $aCapture[3];

        print "$sFirstName, $sLastName, $sLocation";
    }

?>

答案 3 :(得分:0)

使用格式化字符串:

$str = 'jacques.cheminade (espace)';
$result = sscanf($str, '%[^.].%[^ ] (%[^)])');

请注意,如果语法与regex中使用的语法类似,则令牌[^...]不会使用量词来描述字符串的部分而不是单个字符。

相关问题