删除字符串前的 <br /> 标签

Removing the <br /> tags before the strings

我正在 php 从电子邮件正文中获取电子邮件数据。我在删除字符串 This message was created.

之前的 <br /> 标签时遇到问题

这是完整的电子邮件正文:

<br />
<br />
This message was created automatically by mail delivery software.<br />
<br />
A message that you sent could not be delivered to one or more of its<br />
recipients. This is a permanent error. The following address(es) failed: 
<br />
<br />
   fvsafsafsaf@shitmail.com<br />
      retry timeout exceeded

我试过这个:

$top_message = str_replace('<br /> <br /> This message', 'This message', $top_message);

我也试过这个:

$top_message = str_replace('<br /> <br />', '', $top_message);

它不会删除字符串前的 <br /> 标签,因此什么也不会发生。

完整代码如下:

$body = imap_body($mailbox, $email_number, 2);
$email_body = utf8_decode(imap_utf8($body));

$top_message = getBetween($email_body, 'charset=us-ascii', 'exceeded') . 'exceeded';       
$top_message = nl2br($top_message);
$top_message = str_replace('<br /> <br /> This message', 'This message', $top_message);
echo $top_message

我想要实现的是当我从电子邮件正文中获取电子邮件数据时,我想使用 nl2br 为每一行添加 <br /> 标签,然后我想删除字符串 This message was created.

之前的两个 <br /> 标签

我想让它显示成这样:

This message was created automatically by mail delivery software.<br />
<br />
A message that you sent could not be delivered to one or more of its<br />
recipients. This is a permanent error. The following address(es) failed: 
<br />
<br />
   name@example.com<br />
      retry timeout exceeded

能否举例说明如何删除字符串前的两个 <br /> 标签?

谢谢。

使用 preg_replace 和以下正则表达式:/^(<br\s*\/>\s*)*/.

它将删除邮件开头的所有 <br/> 标签。

$str = "<br />
<br />
This message was created automatically by mail delivery software.<br />
<br />
A message that you sent could not be delivered to one or more of its<br />
recipients. This is a permanent error. The following address(es) failed: 
<br />
<br />
   fvsafsafsaf@shitmail.com<br />
      retry timeout exceeded";

print_r(preg_replace('/^(<br\s*\/>\s*)*/', '', $str));

输出:

This message was created automatically by mail delivery software.<br />
<br />
A message that you sent could not be delivered to one or more of its<br />
recipients. This is a permanent error. The following address(es) failed: 
<br />
<br />
   fvsafsafsaf@shitmail.com<br />
      retry timeout exceeded

看起来您在
之间有一个换行符 (\n)。请试试这个:

$top_message = str_replace("/software\.<br \/>\n<br \/>/", 'software.', $top_message);

您可以使用 ltrim() 来根据字符掩码删除字符。
意思是任何 < 和任何 b 和任何 r 和任何 / 和任何 > 直到它找到一个不同的字符。

$message = ltrim($message, "<br/> ");

我添加了 space,因为无论如何它都会是 "optional"。

请注意,如果对我的评论的回答是否定的,这将不起作用,这意味着消息并不总是以 "this message..".
开头 因为如果字符串是 "<br> <br> break free..." 输出将是 "eak free..." 因为字符掩码将删除 "break".
中的 "br" 如果单词以 "rb".

开头,它也会删除

What I am trying to achieve is when I am fetching the email data from the email body, I want to use nl2br to add the <br /> tags for each line and then I want to remove the two <br /> tags before the string "This message was created".

但是你为什么要这么做?只是不要在开头添加 <br/> 标签。

$top_message = nl2br(trim($top_message));