2012-08-03 69 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);