使用正则表达式提取内容

时间:2014-08-09 22:07:03

标签: php regex

我有以下句子:enum('active','disabled','deleted')。我想要的是一个数组:

array(
    [0]=>'active',
    [1]=>'disabled',
    [2]=>'deleted'
)

我如何做到这一点?

2 个答案:

答案 0 :(得分:3)

这个正则表达式之类的东西应该适用于你的字符串。

$sentence = "enum('active','disabled','deleted')";
preg_match_all("/'([^']*)'/", $sentence, $matches);
print_r($matches[1]);

以上代码输出以下内容。

Array
(
    [0] => active
    [1] => disabled
    [2] => deleted
)

正则表达式解释道。

'               //Match opening quote.
    (           //Start capture.
        [^']*   //Match any characters but the end quote.
    )           //End capture.
'               //Match closing quote.

<强>更新

一位意见提供者建议您可能希望保留报价。如果是这种情况,以下正则表达式将起作用。

$s = "enum('active','disabled','deleted')";
preg_match_all("/('[^']*')/", $s, $matches);
print_r($matches[1]);

输出

Array
(
    [0] => 'active'
    [1] => 'disabled'
    [2] => 'deleted'
)

正则表达式解释道。

(               //Start capture.
    '           //Match opening quote.
        [^']*   //Match any characters but the end quote.
    '           //Match closing quote.
)               //End capture.

答案 1 :(得分:1)

您可以使用此正则表达式:

'(\w+?)'

<强> Working demo

enter image description here

MATCH 1
1.  [6-12]  `active`
MATCH 2
1.  [15-23] `disabled`
MATCH 3
1.  [26-33] `deleted`
相关问题