skip to Main Content

Please I need to use php to extract phrases from a text shown below:

Peter,

please check your email for a document I sent, thanks.

Mark,

please I need you to fix my Toyota Camry, thanks.

Mark,

please go and pick up the kids from school, thanks.

Jane,

please go the shop and some items for the house, thanks.

What I need is to display only the phrases relating to Mark. Please note that in this example, Mark has only 2 messages and it could be more residing between Peter and Jane

<?php

$data = "

Peter, <br>

please check your email for a document I sent, thanks.<br>

Mark, <br>

please I need you to fix my Toyota Camry, thanks. <br>

Mark, <br>

please go and pick up the kids from school, thanks. <br>

Jane, <br>

please go the shop and some items for the house, thanks.

";

$start = 'Mark';

$end = 'thanks';

$startIndex = strpos($data, $start);

$endIndex = strpos($data, $end, $startIndex) + strlen($end);

$result = substr($data, $startIndex, $endIndex - $startIndex);

echo $result;

?>

This is what I tried but the result was only the first Phrase

Mark, Please I need to fix my Toyota Camry, thanks.

But I need it to show the second or more phrases relating to Mark.

Please I need help to achieve this.

For this example I am expecting as follows:

Mark, Please I need you to fix my Toyota Camry, thanks. Mark, Please
go and pick up the kids from school, thanks.

2

Answers


  1. Using a while loop to keep going, until the strpos to determine the start index returns false:

    $start = 'Mark';
    
    $end = 'thanks';
    
    $fromPos = 0;
    
    while(false !== ($startIndex = strpos($data, $start, $fromPos))) {
    
        $endIndex = strpos($data, $end, $startIndex) + strlen($end);
    
        $result = substr($data, $startIndex, $endIndex - $startIndex);
    
        $fromPos = $endIndex; // set the new position to search from
                              // on the next iteration
    
        echo $result ."<br><br>";
    }
    
    Login or Signup to reply.
  2. You can explode your string by <br> and search every two items for the key and append the next if found.

    $input = explode("<br>", $yourtext);
    $searchTerm = 'Mark,';
    $output = [];
    for ($index = 0; $index < count($input); $index += 2) {
        if (strpos($input[$index], $searchTerm) !== false) {
            if (isset($input[$index + 1])) $output[]=$input[$index + 1];
        }
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search