【问题标题】:How do I get text containing a certain string between tags如何在标签之间获取包含特定字符串的文本
【发布时间】:2019-02-08 21:19:39
【问题描述】:

请帮我解决 preg_match,我想不通:(

我有很多文本,但我需要捕获“&”之间包含特定文本的所有内容。

例子

"thisip4:isatextexample&ineed.thistext&TXT:&andthis.idontneed&txt:&test.thistext&"

我需要提取 & 之间包含 thistext 的完整文本

结果应该是:ineed.thistext 和:test.thistext

非常感谢提前:)

哦,我试过用这个;

&([^\\n]*thistext[^\\n]*)&

但这不适用于多个 '&'

W

【问题讨论】:

  • 我试过一堆,最接近的是"&([^\\n]*thistext[^\\n]*)&"
  • 所以,正确的标签不是preg-match,而是preg-match-all。请重新标记并添加regexphp

标签: php preg-match-all


【解决方案1】:

您的模式包含匹配除换行符以外的任何 0+ 个字符的 [^\n]*,这使得正则表达式引擎贪婪地匹配任何 & 字符并找到行中的最后一个 &

你可以使用

'~&([^&]*?thistext[^&]*)&~'

然后,获取 Group 1 的值。请参阅regex demo

详情

  • & - 一个 & 字符
  • ([^&]*?thistext[^&]*) - 捕获组 1:
    • [^&]*? - 除& 之外的任何 0+ 个字符,尽可能少
    • thistext - 文字文本
    • [^&]* - 除& 之外的任何 0+ 个字符,尽可能多
  • & - 一个 & 字符

PHP demo:

$str = 'thisip4:isatextexample&ineed.thistext&TXT:&andthis.idontneed&txt:&test.thistext&';
if (preg_match_all('~&([^&]*?thistext[^&]*)&~', $str, $m)) {
    print_r($m[1]);
}
// => Array ( [0] => ineed.thistext [1] => test.thistext )

【讨论】:

  • 非常感谢 :) 但是如果在 & 之间有更多的 'thistext' 实例怎么办?我需要把它们都抓起来
  • @user1973842 显示预期匹配的示例字符串。
  • "thisip4:isatextexample&ineed.thistext&TXT:&andthis.idontneed&txt:&test.thistext&"
  • @user1973842 来晚了,我有点慢。 preg_match_all 将完成这项工作。
猜你喜欢
  • 1970-01-01
  • 2012-10-22
  • 2015-01-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-08-09
  • 1970-01-01
  • 2021-12-31
相关资源
最近更新 更多