代码之家  ›  专栏  ›  技术社区  ›  senty

匹配字符串中的给定字符串并输出数组

  •  -1
  • senty  · 技术社区  · 6 年前

    假设我有一根像

    “学生-约翰·多伊吃了苹果”

    “学生-鲍勃吃桔子”

    我知道这句话包括: ":type - :who ate :noun

    有没有一种方法可以获得一系列动作,使用两个字符串,如:

    $arr = [
       "type" => "Student",
       "who" => "John Doe",
       "noun" => "apples"
    ];
    
    $arr2 = [
       "type" => "Student"
       "who" => "Bob",
       "noun" => "oranges"
    ];
    

    用PHP实现这一点的方法是什么?

    -我想不出任何方法来实现它,所以我不能放任何代码块。

    -也许我甚至不能正确地说出问题的名字,如果你有什么想法的话,我会感激你给我一个更好的名字。

    3 回复  |  直到 6 年前
        1
  •  0
  •   Don't Panic    6 年前

    您还可以在分隔不同部分的字符模式上拆分字符串。

    $result = array_combine(['type', 'who', 'noun'], preg_split('/ - | ate /', $example));
    

    这应该是可靠的,假设没有一个鲍勃吃了一顿或类似的东西。

        2
  •  2
  •   trincot Jakube    6 年前

    可以对命名组使用正则表达式。这假设输入字符串是 $str :

    preg_match("/^(?<type>\w+)\s+-\s+(?<who>\w+(?:\s+\w+)*)\s+ate\s+(?<noun>\w+)$/", 
               $str, $match);
    

    这将设置 $match 比需要多一点,但你可以从中得到你需要的:

    [
       0 => "Student - John Doe ate apples",
       "type" => "Student",
       1 => "Student",
       "who" => "John Doe",
       2 => "John Doe",
       "noun" => "apples",
       3 => "apples"
    ]
    
        3
  •  1
  •   Patrick Q    6 年前

    如果您在更新后的问题中确实有严格的规则,那么这实际上可以在没有任何regex的情况下完成。首先用破折号来表示这个类型,然后用“ate”来表示这个人和这个名词。

    $strings = array("Student - John Doe ate apples", "Student - Bob ate oranges");
    $breakdown = array();
    
    foreach($strings as $line)
    {
        $mainParts = explode("-", $line);
        $type = trim($mainParts[0]);
        $subPart = explode(" ate ", $mainParts[1]);
        $who = trim($subPart[0]);
        $noun = trim($subPart[1]);
    
        $breakdown[] = array("type" => $type, "who" => $who, "noun" => $noun);
    }
    
    var_dump($breakdown);
    

    DEMO