2012-08-03 141 views
1

我想使用正则表达式提取“软件”和它的值“2”的信息信息。请在PHP中查看下面的字符串。使用正则表达式从字符串提取信息

$str = "http://abcfastdirectory.com vs http://www.weblinkstoday.com/detail/link-116406.htm ::-(1)**abcfastdirectory(1)**allows(1)**create(1)**directories(1)**professional(1)**((1)**abcfastdirectory(1)**allows(1)**club(1)**contact(1)**create(2)**details(1)**directories(4)**directory(3)**for(3)**it(1)**our(1)**page(1)**professional(2)**software(2)**"

我如何在PHP中使用正则表达式从上面的字符串中提取信息?

回答

3

如果你只有在“软件(2)”下面应该做的:

preg_match('/software\((?<value>\d+)\)/', $str, $m); 
print $m['value']; 

但是,如果你想每一个喜欢<word>(<num>)您可以使用以下部分匹配:

preg_match_all('/(?<key>\w+)\((?<value>\d+)\)/i', $str, $m); 
foreach ($m['key'] as $i => $key) { 
    print $key.' => '.$m['value'][$i]."\n"; 
} 
0
$software = (int)preg_replace('/.*software\((\d+)\).*/','$1',$str); 
0

试试这个:

$pattern = '/\*\*software\([0-9]+\)\*\*/'; 
preg_match($pattern, $str, $matches); 

// your value will be stored in $matches[1] 
0

你可以试试看,如果是你正在寻找的结果:

<?php 

$str = "http://abcfastdirectory.com vs http://www.weblinkstoday.com/detail/link-116406.htm ::-(1)**abcfastdirectory(1)**allows(1)**create(1)**directories(1)**professional(1)**((1)**abcfastdirectory(1)**allows(1)**club(1)**contact(1)**create(2)**details(1)**directories(4)**directory(3)**for(3)**it(1)**our(1)**page(1)**professional(2)**software(2)**"; 

$matches = array(); 

preg_match_all('#\*\*(.*?)\((\d+)\)\*\*#',$str,$matches, PREG_SET_ORDER); 

print_r($matches); 
相关问题