假设您有纯文本输入。在这些文本中,你可以找到关键字。输入"成本","位置"answers"材料",您想要过滤掉这些关键字后面的单词,以便稍后将它们存储在数据库中具有这些关键字的列下。
你会怎么做?我正在考虑将字符串转换为数组,然后搜索并使用关键字值来计算关键字之间的单词范围。这只是个主意,有人有更好的主意吗?
示例输入:
Cost £45 Materials glue, plastic, wood and nails Location Sale, Manchester North England.
在vars中按如下方式分组:
$cost = "£45";
$materials = "glue, plastic, wood and nails";
$location = "Sale, Manchester North England";
你可以使用这个正则表达式来匹配你的值:
's*'bCost's+(?<cost>.+?)'s*'bMaterials's+(?<material>.+?)'s*'bLocation's+(?<location>.+)
RegEx演示
代码:
$re = '/'s*'bCost's+(?<cost>.+?)'s*'bMaterials's+(?<material>.+?)'s*'bLocation's+(?<location>.+)/';
preg_match($re, $str, $matches);
print_r($matches);
您将在$matches
数组中获得您匹配的值,索引名称指示它匹配的值。
要获得模式匹配的文本,可以使用preg_split
。在这种情况下,我建议匹配任何关键字,使用词边界 ('b
),这允许您以没有特定顺序的关键字解析文本。
正则表达式:
/'b(Cost|Materials|Location)'b/i
为了在preg_split
的结果中包含关键字,我们使用PREG_SPLIT_DELIM_CAPTURE
标志。
preg_split($re, $str, -1, PREG_SPLIT_DELIM_CAPTURE);
还返回第一个关键字匹配之前的文本。我们将使用array_shift()
来丢弃它。
代码:
$re = '/'b(Cost|Materials|Location)'b/i';
$str = "<preceding text> Cost £45 Materials glue, plastic, wood and nails Location Sale, Manchester North England.";
//$re matches keywords, but also captures them... PREG_SPLIT_DELIM_CAPTURE includes the captures in the result
$result = preg_split($re, $str, -1, PREG_SPLIT_DELIM_CAPTURE);
//Remove preceding text
array_shift($result);
print_r($result);
结果Array
(
[0] => Cost
[1] => £45
[2] => Materials
[3] => glue, plastic, wood and nails
[4] => Location
[5] => Sale, Manchester North England.
)
运行以下代码