简体   繁体   English

PHP正则表达式:括号内的字符串

[英]PHP Regular Expression: string from inside brackets

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 not that great at regular expressions. 我在正则表达式方面不怎么好。 Thanks! 谢谢!

so this should do the trick for you: 因此,这应该为您解决问题:

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

This is the PHP syntax: 这是PHP语法:

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

Output: 输出:

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

Enjoy. 请享用。

<?php

/**
 * Regex Quick Extraction - ignore $matches[0];
 */

$a = "Name[value]";

preg_match('/([^\]]*)\[([^\]]*)\]/',$a,$matches);

if(count($matches) > 0) {
    print_r($matches);
}

?>

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
)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM