Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

preg_match PHP pattern search for tokens

Actually I am searching a string for specific tokens which follow a pattern @@text@@ and want to retrieve the tokens from that string into a new array:

my address is @@address@@ and my house is at @@street@@ and the number is @@number@@

I want the tokens in that sentence as an array:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

array[0] = @@address@@
array[1] = @@street@@
array[2] = @@number@@
        $input = 'my address is @@address@@ and my house is at @@street@@ and the number is  @@number@@ or so ';
    preg_match('/@@[^a-z]@@/', $input, $output);
    echo $output[0]; 
    echo $output[1];

Actually all my tokens are surrounded by two @@ but the tokens can vary in number of characters and items.
Any idea

>Solution :

Use preg_match_all() to get all matches. preg_match() just returns the first match.

Your regexp is wrong. [^a-z] matches everything except letters, but you want to match letters. And you need the + quantifier to match more than one.

preg_match_all('/@@[a-z]+@@/', $input, $matches);
$output = $matches[0];
var_dump($output);

DEMO

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading