<?php
$queries="
SELECT col1,col2,col3
FROM users
WHERE id IN (1,2,3,4);
SELECT * FROM references WHERE status = 1
;
SELECT
a.col1
, a.col2
, b.col1
FROM table_a a | <--- Here is the caret, run this query
INNER JOIN table_b b ON b.id_table_a = a.id
WHERE a.id = 5
;
UPDATE table_a SET col1 = 'demo' WHERE id = 3;
-- etc, etc, etc";
$rtrimmed=substr($queries,0,strpos($queries,'|')); // remove substr following pipe
$ltrimmed=substr($rtrimmed,strrpos($rtrimmed,';')+1); // remove substr upto latest semicolon
echo trim($ltrimmed); // remove whitespace on either side
echo "\n---\n";
echo preg_match('~;\s*\K[^;|]*?(?= *\|)~',$queries,$out) ? $out[0] : '';