首页 > 解决方案 > PHP preg_match_all 函数正则表达式

问题描述

下面是一个示例文本片段,我用它来搜索我的 wordpress 网站中的任何主题标签,并将它们创建为一个链接。我正在使用正则表达式 PHP preg_match_all 函数来执行此操作。

这些捕集阱的一个有用附件是#2823 CO² 气体调节器套件,设计用于无法获得或不需要干冰的区域。添加 CO² 气体调节器套件可提高多种蚊子以及黑蝇、稳定蝇、叮咬蠓和新世界沙蝇的捕获率。为了更好地控制调节器的运行时间,建议使用#2880CT定时器来实现无人值守的停止和开始收集时间。

BG-2 Sentinel 陷阱现在可以使用防雨罩。

如需其他替换物品,请参阅:绿色便携包#2880GCC、CO² 发射器喷嘴#2880CO、No-See-Um 网状收集袋#2880CNS1

使用下面的 PHP 行,它会找到该段中提供的主题标签中包含的所有数字和第一个字母,它会忽略并遗漏主题标签中的任何剩余字符。

(例如#2880GCC 只抓取#2880G)

preg_match_all( apply_filters( "wpht_regex_pattern", '/#(\w{4,10})/u'), strip_tags($content), $hashtags );

使用下面的 PHP 行,它会找到所有数字和字母,但会忽略数字后面没有任何字母的任何主题标签。

(例如#2823)

preg_match_all( apply_filters( "wpht_regex_pattern", '/#(\w\w{4,10})/u'), strip_tags($content), $hashtags );

标签: phpregexwordpress

解决方案


使用您现有的REGEX和一个额外的非捕获组?:#它应该与字母数字值前面的所有单词匹配。

 #(?:\w{4,10})

或者

 #(?:[A-Z0-9]+)


<?php
$re = '/#(?:[A-Z0-9]+)/u';
$str = 'A useful accessory to these traps is the #2823 CO² gas regulator kit designed for use in areas where dry ice cannot be obtained or is not desired. Adding the CO² gas regulator kit increases the catch rate for many mosquito species as well as black flies, stable flies, biting midges and New World sand flies. For more control as to how long the regulator runs, using the #2880CT timer is recommended for unattended stop and start collecting times.
    A rain shield is now available for the BG-2 Sentinel trap.
    For other replacement items see: Green Carrying Bag #2880GCC, CO² Emitter Nozzle #2880CO, No-See-Um Mesh Catch Bag #2880CNS1.
';

preg_match_all($re, $str, $matches, PREG_SET_ORDER, 0);
// Print the entire match result
print_r($matches);
?>

演示: https ://3v4l.org/7VPZE


推荐阅读