一.问题:
有如下字符串:
"<str1>name1</str1><str2>name2</str2>"用正则表达式如何取出"name1"和"name2"呢?
二.解答:
2.1:
<?php
$str="<str1>name1</str1><str2>name2</str2>";
preg_match_all("/<[a-z0-9]*>([^<|>]*)<\/[a-z0-9]*>/",$str,$matches);
echo $matches[1][0];
echo $matches[1][1];
?>
2.2
<?php
$str = "<str1>name1</str1><str2>name2</str2>";
preg_match_all('/>([^<]+)</U', $str, $matches);
print_r($matches[1]);
/**
输出结果:
Array ( [0] => name1 [1] => name2 )
*/
?>
2.3
<?php
$str="<str1>name1</str1><str2>name2</str2>";
preg_match_all("/<[a-z0-9]*>([^<|>]*)<\/[a-z0-9]*>/",$str,$matches);
echo $matches[1][0];
echo $matches[1][1];
?>
2.4
<?php
$str="<str1>name1</str1><str2>name2</str2>";
$preg="#<str1>(.*)</str1><str2>(.*)</str2>#";
preg_match($preg,$str,$arr);
echo $arr[1];
echo $arr[2];
?>
三.链接:
php正则表达式在线测试网址:
http://www.spaweditor.com/scripts/regex/index.php点击打开链接
原文地址:
http://s.yanghao.org/program/viewdetail.php?i=211844点击打开链接