[英]Trouble using 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
=========================
謝謝你的幫助。
您可以通過這種方式捕獲顏色后跟單詞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;
}
關於您要處理的數據類型(字符串、對象、數組等)的問題還不夠清楚,但是如果您正在處理字符串,請嘗試
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>
?>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.