尝试将两个单独的正则表达式合并为一个

时间:2015-08-07 13:07:28

标签: php regex

我需要提取括号和单引号括起来的字符串。目前,我正在使用两个正则表达式模式来完成这项工作。使用第一个正则表达式,我从括号中检索字符串,而字符串仍包含单引号,而第二个正则表达式,我可以从中删除单引号。现在,我想一步完成这项工作。在过去的一个小时里,我一直在尝试一些没有任何可行结果的模式;可能是因为我有限的正则表达式知识。因此,您向我提供的任何反馈都将非常有帮助。我还欢迎除正则表达式之外的任何解决方案。

以下是需要解析的示例字符串。

$string = "[('minute stroller workout', 9.0), ('week', 1.0), ('leaving', 1.0), ('times', 1.0), ('guilt', 1.0), ('baby', 1.0), ('beginning', 1.0)]";

# Strip parentheses
preg_match_all('#\((.*?)\)#', $string, $match);
# I am using the first match here
echo $match[1][0]; // output = 'minute stroller workout', 9.0

# Strip single quotes and extract the string
preg_match('~(["\'])([^"\']+)\1~', $match[1][0], $matches);
echo $matches[2]; // output = minute stroller workout (i.e. what we are looking for)  

2 个答案:

答案 0 :(得分:1)

如果我理解正确

preg_match_all('/\(\'([\s\w]*)\', ([\d.]*)\)/', $string, $match);

字符串的输出

array(3) {
  [0]=>
  array(7) {
    [0]=>
    string(32) "('minute stroller workout', 9.0)"
    [1]=>
    string(13) "('week', 1.0)"
    [2]=>
    string(16) "('leaving', 1.0)"
    [3]=>
    string(14) "('times', 1.0)"
    [4]=>
    string(14) "('guilt', 1.0)"
    [5]=>
    string(13) "('baby', 1.0)"
    [6]=>
    string(18) "('beginning', 1.0)"
  }
  [1]=>
  array(7) {
    [0]=>
    string(23) "minute stroller workout"
    [1]=>
    string(4) "week"
    [2]=>
    string(7) "leaving"
    [3]=>
    string(5) "times"
    [4]=>
    string(5) "guilt"
    [5]=>
    string(4) "baby"
    [6]=>
    string(9) "beginning"
  }
  [2]=>
  array(7) {
    [0]=>
    string(3) "9.0"
    [1]=>
    string(3) "1.0"
    [2]=>
    string(3) "1.0"
    [3]=>
    string(3) "1.0"
    [4]=>
    string(3) "1.0"
    [5]=>
    string(3) "1.0"
    [6]=>
    string(3) "1.0"
  }
}

答案 1 :(得分:0)

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

***********************
Expected presence of child node 'baz' but was 'null' - comparing <baz...> at /foo[1]/baz[1] to  at null
Node was removed
***********************
***********************
Expected presence of child node 'null' but was 'xyzzy' - comparing  at null to <xyzzy...> at /foo[1]/xyzzy[1]
Node was added
***********************