如何匹配两个其他已知字符串之间的字符串,而没有其他字符与REGEX?
我想提取两个其他字符串之间的字符串。字符串恰好在HTML标签内,但我想避免关于是否应该使用正则表达式解析HTML的对话(我知道我不应该用stristr()解决问题,但想知道如何去做。与如何匹配两个其他已知字符串之间的字符串,而没有其他字符与REGEX?
正则表达式的字符串可能是这样的:
...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]);
输出
美国华盛顿座tle
谢谢。这是一个很好的观点,会避免一个错误,但它仍然不匹配任何东西。 – codecowboy 2012-04-19 12:03:34
我测试了它并为我工作。我更新了我的答案。 – stema 2012-04-19 12:28:08
谢谢。它不是在当地工作 - 可能出于其他原因,所以我会接受答案。 – codecowboy 2012-04-19 12:37:06