PHP Regular Expression: string from inside brackets

前端 未结 3 1362
再見小時候
再見小時候 2020-12-20 07:16

I have a string:

$a = \"Name[value]\";

How do I get the \'Name\' and \'value\' portions of string into variables from this string? I\'m no

相关标签:
3条回答
  • 2020-12-20 07:56
    <?php
    
    /**
     * Regex Quick Extraction - ignore $matches[0];
     */
    
    $a = "Name[value]";
    
    preg_match('/([^\]]*)\[([^\]]*)\]/',$a,$matches);
    
    if(count($matches) > 0) {
        print_r($matches);
    }
    
    ?>
    
    0 讨论(0)
  • 2020-12-20 07:58

    so this should do the trick for you:

    (.*)\[(.*)\]
    

    This is the PHP syntax:

    <?php
    $subject = "Name[value]";
    $pattern = '/(.*)\[(.*)\]/';
    preg_match($pattern, $subject, $matches);
    print_r($matches);
    ?>
    

    Output:

    Array
    (
        [0] => Name[value]
        [1] => Name
        [2] => value
    )
    

    Enjoy.

    0 讨论(0)
  • 2020-12-20 08:10

    Try this:

     <?php
    $a = "Name[value]";
    preg_match('/(?<name>.*?)\[(?<value>.*[^\]]+)/', $a, $matched); 
     echo '<pre>'; 
     print_r($matched);
    ?>
    

    output:

    Array
    (
        [0] => Name[value
        [name] => Name
        [1] => Name
        [value] => value
        [2] => value
    )
    
    0 讨论(0)
提交回复
热议问题