首页 > 解决方案 > 使用 preg_match_all 时遇到问题

问题描述

如何使用preg_match_all函数从以下示例中检索所有颜色:

Name: jonathan
Color: blue
Gender: male
=========================
Name: anthony
Color: yellow
Gender: male
=========================
Name: sandra
Color: pink
Gender: female
=========================
Name: marry
Color: white
Gender: female
=========================
Name: david
Color: black
Gender: male
=========================

谢谢你的帮助。

标签: phppreg-match-all

解决方案


您可以通过这种方式捕获单词后面的颜色Color:

<?php

$re = '/Color: (.*)/m';
$str = 'Name: jonathan
Color: blue

Gender: male
Name: anthony
Color: yellow

Gender: male
Name: sandra
Color: pink

Gender: female
Name: marry
Color: white

Gender: female
Name: david
Color: black

Gender: male';

preg_match_all($re, $str, $matches, PREG_SET_ORDER, 0);

// Print the entire match result
// Print the entire match result
foreach($matches as $match){
    echo $match[1].PHP_EOL;
}

推荐阅读