如何使用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
=========================
谢谢你的帮助。
您可以通过这种方式捕获颜色,然后单词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;
}
关于你正在处理什么数据类型(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>
?>