php - 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 );
解决方案
使用您现有的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);
?>
推荐阅读
- javascript - 将时间转换为关键帧动画百分比
- api - 如何在 GitHub 公共存储库中读取文件的内容
- linux - 给定一个从客户端到服务器的已建立 tcp 连接,是否在没有服务器显式调用接受的情况下解决了第二个连接?
- graphics - 光线投射优化
- ruby - 从包含的文件调用时,Ruby 字符串插值不起作用
- c# - IntegerUpDown 控件在 Textbox IsFocused 时更改背景
- python - 可重用可迭代的语法?
- javascript - 在相同表单中存在按钮的情况下,如何在文本输入字段上触发输入键事件?
- python-3.x - 将包含字母、数字、符号或标签的元组转换为字符串
- javascript - AJAX Post 方法中的 400 Bad Response Error