PHP Regex - how to remove string after “Newline * regards”

Phili

New Member
#1
I've got strings like the following:
Mã:
Hi X

Blah

Kind regards
ABC
And
Mã:
Hi X

Blah

Regards
CBA
So the key is the newline and the word "regards" (case insensitive). I'd like to use PHP to get the part of the string before the line that contains "regards". E.g. for these examples, the result should just be:
Mã:
Hi X

Blah
I've tried the below but it doesn't work as intended in some cases (E.g. if "Kind" appears multiple times in the string). Thanks in advance!
Mã:
$matches = array();
        if (preg_match("/\n(.*?)regards/i", $message, $matches) == 1) {
            $stop_at = $matches[1];
            $split = explode($stop_at,$message);
            $message = $split[0];
        }
 

Admin

Administrator
Thành viên BQT
#2
What you're really after is a regex that handles multi-line strings. For this, you can use the m flag (PCRE_MULTILINE).

I would use preg_split() to split the string on your token, for example

Mã:
$found = trim(preg_split('/^.*regards$/im', $message, 2)[0]);
Demo ~ https://3v4l.org/idMcP

Some notes:

  • I've used trim() to remove the empty line after "Blah" (your examples exclude it)
  • I've set a limit of 2 on preg_split(). This is redundant given you're only retrieving the first split but in my head, it means PHP does less work (realities may vary).
  • This might fail if a line ends in a word ending in "regards" but not necessarily the word "regards", for example this word I just made up "goregards" (it's like a shin guard but for viscera).
 
Top