skip to Main Content

I am new in PHP. I am trying to extract subject and body text from the string like below

$string = "Subject:
Update on Your Ticket: ID {{ random_number }}

Body:
Hello,

Your ticket has been recently updated on {{ date }}. We kindly request you to review and acknowledge the changes made.

If you have any further updates or queries regarding your ticket, please don't hesitate to respond to this email.

Best Regards,
{{ sender_name }}";

What I want from it is like

$subject = "Update on Your Ticket: ID {{ random_number }}";
$body ="Hello,
    
    Your ticket has been recently updated on {{ date }}. We kindly request you to review and acknowledge the changes made.
    
    If you have any further updates or queries regarding your ticket, please don't hesitate to respond to this email.
    
    Best Regards,
    {{ sender_name }}"

I must clear that this is not static string, it will be dynamic string given by chat gpt. I have tried some questions and answers like

But not getting any idea to solve puzzle from last 2 hours. Let me know if any one here can help me for solve the issue.

2

Answers


  1. If you are sure that Body: will never be repeated, you can use simple functions to do this:

    // Get text before and after “Body:”
    $parts = explode('Body:', $string);
    
    // Remove “'Subject:” and the whitespaces
    $subject = trim(str_replace('Subject:', '', $parts[0]));
    // Remove the whitespaces
    $body = trim($parts[1]);
    

    Try it online

    Login or Signup to reply.
  2. With regular expressions:

    preg_match_all('/^Subject:n(.+)nBody:n(.+)$/s', trim($string), $matches);
    
    $subject = $matches[1][0];
    $body = $matches[2][0];
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search