php - 括号中特定 ID 的正则表达式
问题描述
我对正则表达式没有信心。用 PHP 代码写这个。
我需要能够过滤掉遵循这种格式的字符串,其中数字可以是 4~6 位(仅限数字):
$input = "This is my string with a weird ID added cause I'm a weirdo! (id:11223)";
我可以通过查找空格的最后一个位置来简单地删除最后一个单词strrpos();
(看起来它们都没有来自 JSON 提要的尾随空格),然后使用substr();
它来剪切它。但我认为更优雅的方式是子字符串。预期的输出将是:
$output = trim(preg_replace('[regex]', $input));
// $output = "This is my string with a weird ID added cause I'm a weirdo!"
所以这个正则表达式应该与方括号、id: 部分和任何连续的数字匹配,例如:
(id:33585)
(id:1282)
(id:9845672)
打算使用该preg_replace()
功能从数据馈送中删除这些。不要问我为什么他们决定在描述字符串中包含一个 ID……这也让我大吃一惊,为什么它不是 JSON 提要中的一个单独的列。
解决方案
尝试使用模式\(id:\d+\)
:
$input = "Text goes here (id:11223) and also here (id:33585) blah blah";
echo $input . "\n";
$output = preg_replace("/\(id:\d+\)/", "", $input);
echo $output;
这打印:
Text goes here (id:11223) and also here (id:33585) blah blah
Text goes here and also here blah blah
这里有一个边缘情况,您可以在替换后留下的可能(不需要的)提取空白中看到它。我们也可以尝试变得复杂并删除它,但是您应该说明您期望的输出是什么。
推荐阅读
- python - 不一致的通信链路故障 (10060) 错误
- html - 如何仅在css文件中设置句子中单个单词的样式而不添加额外的标签(例如span)并且没有js
- windows - 如何启用 TPM 测量启动并在 Windows 10 中查看 pcr 值?
- reactjs - 想要改变 React Material-UI DataGrid 过滤器菜单弹出的位置
- shell - Openstack:创建实例时无法绑定端口
- javascript - Webpack:从 webpack.config.js 到 webpack.dev.js
- elasticsearch - 来自 ElasticSearch 的搜索结果
- reactjs - 未捕获的类型错误:无法读取未定义的属性“结果” - ReactJS
- r - is_corpus_df(corpus) 中的错误:all(names(corpus)[1L:2L] == c("doc_id", "text")) 不是 TRUE
- typescript - 打字稿:将对象[名称:类型]转换为接口