我想在另外两个字符串之间提取一个字符串。字符串碰巧在 HTML 标签中,但我想避免讨论我是否应该使用正则表达式解析 HTML(我知道我不应该并且已经解决了 stristr() 的问题),但想知道如何使用正则表达式来做到这一点。
字符串可能如下所示:
...uld select “Apply” below.<br/><br/><b>Primary Location</b>: United States-Washington-Seattle<br/><b>Travel</b>: Yes, 75 % of the Time <br/><b>Job Type</b>: Standard<br/><b>Region</b>: US Service Lines: ASL - Business Intelligence<br/><b>Job</b>: Business Intelligence<br/><b>Capability Group</b>: Con/Sol - BI&C<br/><br/>LOC:USA
我对<b>Primary Location</b>: United States-Washington-Seattle<br/>
感兴趣,想提取"美国-华盛顿-西雅图"
我尝试了'(?<=<b>Primary Location</b>:)(.*?)(?=<br/>)'
在 RegExr 中工作但不适用于 PHP:
preg_match("/(?<=<b>Primary Location</b>:)(.*?)(?=<br/>)/", $description,$matches);
您使用/
作为正则表达式分隔符,因此如果要从字面上匹配它或使用其他分隔符,则需要对其进行转义
preg_match("/(?<=<b>Primary Location</b>:)(.*?)(?=<br/>)/", $description,$matches);
自
preg_match("/(?<=<b>Primary Location<'/b>:)(.*?)(?=<br'/>)/", $description,$matches);
或者这个
preg_match("~(?<=<b>Primary Location</b>:)(.*?)(?=<br/>)~", $description,$matches);
更新
我刚刚在 www.writecodeonline.com/php 上测试了它,并且
$description = "uld select “Apply” below.<br/><br/><b>Primary Location</b>: United States-Washington-Seattle<br/><b>Travel</b>: Yes, 75 % of the Time <br/><b>Job Type</b>: Standard<br/><b>Region</b>: US Service Lines: ASL - Business Intelligence<br/><b>Job</b>: Business Intelligence<br/><b>Capability Group</b>: Con/Sol - BI&C<br/><br/>LOC:USA";
preg_match("~(?<=<b>Primary Location</b>:)(.*?)(?=<br/>)~", $description, $matches);
print_r($matches);
正在工作。输出:
数组 ( [0] => 美国-华盛顿-西雅图[1] => 美国-华盛顿-西雅图 )
您也可以摆脱捕获组并执行
$description = "uld select “Apply” below.<br/><br/><b>Primary Location</b>: United States-Washington-Seattle<br/><b>Travel</b>: Yes, 75 % of the Time <br/><b>Job Type</b>: Standard<br/><b>Region</b>: US Service Lines: ASL - Business Intelligence<br/><b>Job</b>: Business Intelligence<br/><b>Capability Group</b>: Con/Sol - BI&C<br/><br/>LOC:USA";
preg_match("~(?<=<b>Primary Location</b>:).*?(?=<br/>)~", $description, $matches);
print($matches[0]);
输出
美国-华盛顿-西雅图