0

我想在其他两个字符串之间提取一个字符串。字符串恰好在 HTML 标记内,但我想避免讨论我是否应该使用正则表达式解析 HTML(我知道我不应该并且已经解决了 stristr() 的问题,但想知道该怎么做用正则表达式。

一个字符串可能如下所示:

...uld select &#8220;Apply&#8221; 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);

4

1 回答 1

1

您用作/正则表达式分隔符,因此如果您想逐字匹配或使用不同的分隔符,则需要对其进行转义

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

输出

美国-华盛顿-西雅图

于 2012-04-19T11:52:05.390 回答