简体   繁体   中英

Extract information from string using regular expression

I want to extract information information of "software" and its value "2" using regular expression. please have a look into below string in 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)**"

How can I extract information from above string using regular expression in PHP?

If you are only after "software(2)" the following should do:

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

However if you want to match every part that like <word>(<num>) you can use the following:

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

Try this:

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

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

You can try this and see the result if it is what you are looking for :

<?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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM