Php preg_match多次出现,返回唯一数组

时间:2016-12-30 21:55:19

标签: php regex preg-match

我希望能够提取字符串的某些部分并返回唯一数组。这是我的字符串:

$string = "
  <div> some text goes here... **css/method|1|2**</div>
  <div>**php/method|3|4**</div>
  <div>**html|method|6|9** and more text here</div>
  <div>**html/method|2|5**</div>
";

使用preg_match_all()

$pattern = "/**(.*?)**/";
preg_match_all($pattern, $string, $matches);

我可以从字符串中提取所有部分,但我需要更进一步,只返回以下内容:

css,php和html。

最终数组应如下所示:

$result = array("css", "php", "html");

所以基本上,我需要在这种情况下消除重复值“html”,以及在反斜杠或管道之前提取每个值。我不关心方法部分以及后续的内容。

1 个答案:

答案 0 :(得分:2)

使用preg_match_allarray_unique函数的解决方案:

preg_match_all("~\*\*([^/|*]+)(?=[/|])~", $string, $matches);
$result = array_unique($matches[1]);
print_r($result);

输出:

Array
(
    [0] => css
    [1] => php
    [2] => html
)

(?=[/|]) - 正向前瞻断言,匹配单词后跟其中一个字符/|

更新 :忽略来自匹配更新正则表达式模式的标记,并使用以下~\*\*([^/|*<>]+)(?=[/|])~