Search code examples
phppreg-match

PHP preg_match two values how to check with || operator


I need to check if string contains F: # { blabla } or # F: { blabla } how to do that with preg_match? I try with this code but it does not run code when i add # before letter F:

if (preg_match('/F: ([A-za-z0-9]+) ([A-za-z0-9]+)( # (\{.*?\})){0,1}/', $line, $match) || preg_match('/# F: ([A-za-z0-9]+) ([A-za-z0-9]+)( # (\{.*?\})){0,1}/', $line, $match)) {
    echo 'STRING Contains F: and # F:';
}

Here is example:

<?php
$line = 'F: bbb bbb # { startdate=2015-08-10 | enddate=2015-11-10 | info=info | dealer=person548 | test=0 | emu=unknown | free=0 }';
/* $line = '# F: bbb bbb # { startdate=2015-08-10 | enddate=2015-11-10 | info=info | dealer=person548 | test=0 | emu=unknown | free=0 }'; */
if (preg_match('/(# )?F: ([A-za-z0-9]+) ([A-za-z0-9]+)( # (\{.*?\})){0,1}/', $line, $match)) {
    echo 'STRING Contains F: and # F:';
}

Solution

  • The pattern should look like this:

    $pattern = '/(F: #|# F:) \{ blabla \}/';
    

    Note the capturing ground (F: #|# F:). It matches one of the patterns separated by the |.

    Try it online