繁体   English   中英

使用正则表达式从字符串中提取信息

[英]Extract information from string using regular expression

我想使用正则表达式提取“软件”及其值“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中的正则表达式从上面的字符串中提取信息?

如果您只是在“软件(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";
}
$software = (int)preg_replace('/.*software\((\d+)\).*/','$1',$str);

尝试这个:

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

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

您可以尝试这个并查看结果,如果它是您正在寻找的:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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