0

What I have is a long string that I extracted from an uploaded file, I am trying to split this string according to keywords, I know there are many answers here about splitting and exploding a string but none of them gave me a clue on how to solve my problem since I am not relying on white spaces or a specific number of characters, the only factor I have is the occurrences of certain keywords, here is what I tried:

    $text = readMyFile('filename.txt');
    //Now $text contains a very long unformatted text but there are keywords
    $keyword = 'ADDRESS:'; //there is only one occurrence of ADDRESS:
    $address = explode($keyword, $text);

    print_r($address); //$address[1] contains all text after the keyword ADDRESS:

but I have other keywords to search for, and now I have an array of two elements, all text before and after the keyword, how is it possible to repeat this procedure over and over to extract all text in between keywords, for example in between 'ADDRESS:' and 'JOB TITLE' so that I get the full address from the original document in one element of an array

1 Answer 1

1

You can probably use preg_match_all() for this:

$keywords = ['ADDRESS', 'JOB TITLE'];
$pattern = sprintf('/(?:%s):(.*?)/', join('|', array_map(function($keyword) {
    return preg_quote($keyword, '/');
}, $keywords)));

preg_match_all($pattern, $text, $matches);

The text that comes before the first keyword is skipped.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.