【问题标题】:How to find a pattern in string using PHP如何使用 PHP 在字符串中查找模式
【发布时间】:2015-04-29 22:14:18
【问题描述】:

我有一个文本,我想返回字符串,直到第一次出现“不包括该模式”的模式

这是我的文字

Hello World,
I should see this and only this <br> test<br>
On Apr 29, 2015, at 11:50 AM, Blah &lt;<a href=
"mailto:blah@blah.com">blah@blah.com</a>&gt;
wrote:<br>

我正在寻找的模式是这样的

On____<______>___ wrote:

这是一个文本示例

On Apr 29, 2015, at 11:50 AM, Blah &lt;<a href=
"mailto:blah@blah.com">blah@blah.com</a>&gt;
wrote:<br>

找到这个模式尝试了这个代码

$pattern = '~On.*?<([^>]*)>\s+wrote:~';
$isWebApp = preg_match($pattern, $message, $matches);

if($isWebApp !== false && isset($matches[0]) ){
    $pos = strpos($message, $matches[0]);
    $message = substr($message, 0, $pos);
}
echo $message;

但它不起作用。

我的预期输出是

Hello World,
    I should see this and only this <br> test<br>

如何更正模式以使其找到我要查找的内容?

【问题讨论】:

  • 在“开”之前还是在“开”之后?
  • @PedroLobito 似乎每个人都在潜伏,直到烟雾散去 :)
  • @Mike 你能用你的预期输出更新你的问题吗?
  • 你一直在改变你的问题,令人沮丧......对不起,没有更多的帮助。
  • @Mike 您的问题不清楚且自相矛盾...我根据您的预期输出进行了回答,但不确定您现在是否想要

标签: php regex preg-match


【解决方案1】:

你可以使用这个正则表达式:

([\s\S]*?)On[\s\S]*?wrote

Working demo

php代码

$re = "/([\\s\\S]*?)On[\\s\\S]*?wrote/"; 
$str = "Hello World,\nI should see this and only this <br> test<br>\nOn Apr 29, 2015, at 11:50 AM, AccoRDI &lt;<a href=\n\"mailto:blah@blah.com\">blah@blah.com</a>&gt;\nwrote:<br>"; 

preg_match($re, $str, $matches);

比赛信息

MATCH 1
1.  [0-59]  `Hello World,
I should see this and only this <br> test<br>
`

顺便说一句,如果你想遵循你的模式:On____&lt;______&gt;___ wrote:。你可以使用这个正则表达式:

([\s\S]*?)On[\s\S]*?<[\s\S]*?>[\s\S]*?wrote

【讨论】:

  • 测试中可能有很多On,所以我需要识别模式并返回它之前的所有内容
  • @Mike 已修复,如果答案中的更新是您想要的,请告诉我
【解决方案2】:
$x = '
Hello World,
I should see this and only this <br> test<br>
On Apr 29, 2015, at 11:50 AM, Blah &lt;<a href=
"mailto:blah@blah.com">blah@blah.com</a>&gt;
wrote:<br>
';

    preg_match('/On(.*?)wrote/s',$x,$m);

    echo $m[1];

将输出:

2015 年 4 月 29 日上午 11:50,Blah

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-08-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-07
    • 2020-09-06
    • 1970-01-01
    相关资源
    最近更新 更多