[英]PHP preg_match and regular expression
我是PHP新手
我正在尝试获取链接的主题号,但不起作用。
echo $topicsave
为空。
这是我的代码。
$data = '
<a href="http://forums.inwing.com/index.php/topic,40500.0.html">test_curl</a>
';
preg_match_all('/\<a[^\?]+\/([^\"]+)\.\s*\>test_curl\<\/a\>/', $data, $match);
echo '<pre>',htmlspecialchars(print_r($match, true)),'</pre>';
if( count($match[0])){
foreach($match[1] as $vl){
preg_match_all('/topic\,([0-9]+\.[0-9]+)/', $vl, $m1);
if(count($m1[1]))
$topicsave = $m1[1][0];
echo $topicsave;
}
}
我想获取主题号40500
请帮助我,主题是变量,例如120或2536
或12456
。
谢谢。
要从链接中提取主题编号,可以使用以下正则表达式。
正则表达式: topic,(\\d+(\\.\\d+)*)\\.html
说明:这样做是在提供您到regex的链接并提取topic,
和.html
之间的数字。
您可以这样做:
$re = "/topic,(?'topic'\\d+)/";
$str = "<a href=\"http://forums.inwing.com/index.php/topic,40500.0.html\">test_curl</a>";
preg_match($re, $str, $matches);
echo $matches['topic'];
将输出:
40500
我在这里使用的(?'topic'\\\\d+)
是一个命名组 。 它允许您使用您使用的名称(此处为topic
)从匹配项中检索数据。
如果您需要进行实时测试,那么Regex 101很棒。
试试这个解决方案:
$data = '<a href="http://forums.inwing.com/index.php/topic,40500.0.html">test_curl</a>';
preg_match_all('/topic,(.*?)\..*\.html/s', $data, $match);
echo $match[1][0]; // Output: 40500
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.