【问题标题】:php Regex before a character and before another onephp Regex 在一个字符之前和另一个字符之前
【发布时间】:2017-05-15 12:00:07
【问题描述】:

我有一个列表:

firstname.lastname (location)

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

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

我找到了:

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

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

【问题讨论】:

  • regexr.com .. 去这里试试自己
  • 第一步 google 正则表达式,然后告诉我们你尝试了什么regex101.com
  • 我找到了,我不能做我想做的事,我确实找到了位置,或者名字,但不是所有 3 个一起,或者姓氏

标签: php regex


【解决方案1】:

你可以不用正则表达式:

$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], ')');

【讨论】:

  • 谢谢,我不知道为什么要使用正则表达式,当我尝试查找位置时在 google 上发现了一些东西,并且似乎合乎逻辑地继续使用正则表达式作为名称。
【解决方案2】:

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

【讨论】:

    【解决方案3】:

    使用正则表达式并不太难。但是,您的困惑可能源于该示例字符串中的几个字符在 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";
        }
    
    ?>
    

    【讨论】:

    • 你应该把\s*改成\s+,否则就没有意义了。
    • OP没有提到空间是否强制执行,所以我没有强制执行。
    • 非常感谢,这是一个非常好的开始,但是如果位置中有点,或者名称中有空格,我会尝试弄清楚
    • \w+ 更改为.+?
    • 非常感谢 Toto :)
    【解决方案4】:

    使用格式化字符串:

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

    请注意,如果语法看起来与正则表达式中使用的语法相似,则标记 [^...] 不使用量词,因为它们描述了字符串的一部分而不是单个字符。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-03-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-01-07
      • 1970-01-01
      相关资源
      最近更新 更多