从字符串中提取多个匹配项

时间:2014-04-29 20:45:42

标签: php

我想从更大的字符串中提取多个字符串。

以下是Google AdWords API返回的错误。此特定示例在trigger:之后有两个引用的实例,但可能有几个。

从较大的字符串中提取x量的引用实例并将其保存在数组中的最佳方法是什么?

是否有可用的PHP函数,还是应该使用implode和循环?

任何想法都会受到赞赏,我很乐意破解代码,只需要一些指示。

非常感谢

  

广告组更新失败:[AdGroupServiceError.DUPLICATE_ADGROUP_NAME @ operations [6] .operand.name;触发器:'prince2 training west yorkshire',AdGroupServiceError.DUPLICATE_ADGROUP_NAME @ operations [8] .operand.name;触发器:'王子ii训练和考试']

1 个答案:

答案 0 :(得分:1)

这是你可以做的

$str = "AdGroup update failed: [AdGroupServiceError.DUPLICATE_ADGROUP_NAME @ operations[6].operand.name; trigger:'prince2 training west yorkshire', AdGroupServiceError.DUPLICATE_ADGROUP_NAME @ operations[8].operand.name; trigger:'prince ii training and exam']";

preg_match_all("/'(.*?)'/im",$str,$match);

print_r($match[1]);

更具体地说,如果它始终在trigger:之后,您可以使用以下

preg_match_all("/trigger:'(.*?)'/im",$str,$match);

输出::

Array
(
    [0] => prince2 training west yorkshire
    [1] => prince ii training and exam
)

<强>解释

/'(.*?)'/im
    ' matches the character ' literally
    1st Capturing group (.*?)
        .*? matches any character (except newline)
            Quantifier: Between zero and unlimited times, as few times as possible, expanding as needed [lazy]
    ' matches the character ' literally
    i modifier: insensitive. Case insensitive match (ignores case of [a-zA-Z])
    m modifier: multi-line. Causes ^ and $ to match the begin/end of each line (not only begin/end of strin