php regex从字符串中提取多个匹配项
发布时间:2020-12-13 18:04:44 所属栏目:PHP教程 来源:网络整理
导读:我正在尝试使用php正则表达式从一个字符串中提取多个部分/条件…让我告诉你我在说什么;这是总文件内容的摘录(真实内容包含数百个这样的分组): part "C28"{ type : "1AB010050093",%cadtype : "1AB010050094",shapeid : "2_1206",descr : "4700.0000 pFarad
我正在尝试使用php正则表达式从一个字符串中提取多个部分/条件…让我告诉你我在说什么;这是总文件内容的摘录(真实内容包含数百个这样的分组):
part "C28" { type : "1AB010050093",%cadtype : "1AB010050094",shapeid : "2_1206",descr : "4700.0000 pFarad 10.00 % 100.0 - VE5-VS3",insclass : "CP6A,CP6B",gentype : "RECT_032_016_006",machine : "SMT",%package : "080450E",%_item_number: "508",%_Term_Seq : "" } part "C29" { type : "1AB008140029",descr : "150.0000 pFarad 5.00 % 100.0 Volt NP0 CERAMIC CAPACITOR",%_item_number: "3",%_Term_Seq : "" } 如您所见,摘录中的数据重复两次.我需要搜索整个文件并提取以下内容: >“part”之后的字符串 – 这将是“C28”或“C29” 所以,基本上,我需要从这个文件中获取所有部件引用和相关类型…而且我不确定这样做的最佳方法. 如果需要更多信息,请告知我们…提前感谢!
描述
这个表达式将: >将组名称捕获为ref 请注意,这是一个单独的表达式,因此您将使用x选项,以便正则表达式引擎忽略空格. ^parts"(?P<ref>[^"]*)"[^{]*{ (?:(?=[^}]*sdescrs*:s+"(?P<descr>[^"]*)"))? (?=[^}]*stypes*:s+"(?P<type>[^"]*)") PHP代码示例: 输入文本 part "C28" { type : "1AB010050093",%_Term_Seq : "" } part "C30" { type : "1AB0081400 30",shapeid : "2_1206 30",CP6B 30",gentype : "RECT_032_016_006 30",machine : "SMT 30",%package : "080450E 30 ",%_item_number: "3 30 ",%_Term_Seq : "30" } 码 <?php $sourcestring="your source string"; preg_match_all('/^parts"(?P<ref>[^"]*)"[^{]*{ (?:(?=[^}]*sdescrs*:s+"(?P<descr>[^"]*)"))? (?=[^}]*stypes*:s+"(?P<partnumber>[^"]*)")/imsx',$sourcestring,$matches); echo "<pre>".print_r($matches,true); ?> 火柴 $matches Array: ( [ref] => Array ( [0] => C28 [1] => C29 [2] => C30 ) [descr] => Array ( [0] => 4700.0000 pFarad 10.00 % 100.0 - VE5-VS3 [1] => 150.0000 pFarad 5.00 % 100.0 Volt NP0 CERAMIC CAPACITOR [2] => ) [partnumber] => Array ( [0] => 1AB010050093 [1] => 1AB008140029 [2] => 1AB0081400 30 ) ) (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |