phppreg-matchstripos

preg match and stripos


I have an csv import function. There is in the csv a column like this ''1. Informatik, Bachelor, 2015, 1. Fachsemester'' or this '' 1. Mathematik, LA Bachelor Gymnasien, 2015,''

If in the line exists 'LA' , so $fachrichtung='Lehramt', if there is no LA, $fachrichtung is the first word after the number. here: 1. Informatik, Bachelor, 2015, 1. Fachsemester $fachrichtung= 'Informatik'. But if the first word ist not Informatik or Physik, then $fachrichtung= 'Sonstige'.

preg_match( '/[\d]+\.(?P<fach>[\w\s]+)/ius', $tmp[6], $aMatches );
$fachrichtung = ( false !== stripos($tmp[6], ', LA ') ) ? "Lehramt" : trim( $aMatches['fach'] );

how can i include the last condition ('Sonstige') in code above? I tried it with if and else but it doesn't function. thanks


Solution

  • You need to check the value of the fach group later and assign the value to $fachrichtung accordingly:

    // $tmp = '1. Mathematik, LA Bachelor Gymnasien, 2015,'; // => Sonstige
    $tmp = '1. Informatik, Bachelor, 2015, 1. Fachsemester'; // => Informatik
    $fachrichtung = '';
    if (preg_match( '/\d+\.(?P<fach>[\w\s]+)/ius', $tmp, $aMatches )) { 
       if (true === stripos($tmp, ', LA ') ) {
          $fachrichtung = "Lehramt";
       } else if ("Informatik" !== trim( $aMatches['fach'] ) && "Physik" !== trim( $aMatches['fach'] )) {
          $fachrichtung = "Sonstige";
       } else {
          $fachrichtung = trim( $aMatches['fach'] );
       }
       echo $fachrichtung;
    }
    

    See the PHP demo.

    The regex is OK, I just added a couple of if ... else.

    The else if ("Informatik" !== trim( $aMatches['fach'] ) && "Physik" !== trim( $aMatches['fach'] )) checks if the fach group value is not equal to trimmed Informatik or Physik. If it is not equal, set Sonstige value. Else, set the fach group value.