使用preg_match_all时遇到麻烦

问题描述 投票:-4回答:2

如何使用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
=========================

谢谢你的帮助。

php preg-match-all
2个回答
0
投票

您可以通过这种方式捕获颜色,然后单词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;
}

0
投票

关于你正在处理什么数据类型(String,Object,array等)的问题还不够明确但是如果你正在处理字符串试试

preg_match_all ('/(C|c)olor:\w*?\s.*/m', $yourString, $resultArray)

来自php的preg_match_all通过字符串中的表达式返回所有匹配的数组,在这种情况下,它将是字符串中的所有颜色。

完整的例子可以

<?php

$myString = 
'Name: jonathan
Color: blue

Gender: male
Name: anthony
Color: yellow

Gender: male
Name: sandra
Color: pink';

preg_match_all('/(C|c)olor:\w*?\s.*/m', $myString, $resultArray);

<pre>
printr($resultArray)
</pre>

?>
© www.soinside.com 2019 - 2024. All rights reserved.