MoteCL
MoteCL

Reputation: 228

Remove words in php when finding a -

I have the following code where cutting words. If in front of the word I find a - I cut the word, leaving only the first part

<?php

    $values = array("PANELEGP00001",
    "PANELEGP00003",
    "PANELEGP00001-1",
    "PANELEGP00002-TOS",
    "PANELEGP00004-2",
    "LIVOR-44_900_2100",
    "004-00308D" 
  );

  foreach ($values as $i => &$value) {
      $words = explode("-", $value);      
        if (preg_match("/[a-z]/i", $words[1])) {       
          $value = $words[0];
      }
  }

    PANELEGP00001
    PANELEGP00003
    PANELEGP00001-1
    PANELEGP00002   //I REMOVE THE WORD TOS
    PANELEGP00004-2
    LIVOR-44_900_2100
    004             // This should not be cut, it because there is a letter
               at the end. I want to cut only if I find a letter at the beginning

?>

I want to cut only if I find a letter at the beginning like this PANELEGP00002-TOS but not in this one 004-00308D or this one 004-0D3080 only If a letter in front of -

Upvotes: 0

Views: 50

Answers (2)

Werner
Werner

Reputation: 449

Based on ctype_alpha().

  $values = array("PANELEGP00001",
                  "PANELEGP00003",
                  "PANELEGP00001-1",
                  "PANELEGP00002-TOS",
                  "PANELEGP00004-2",
                  "LIVOR-44_900_2100",
                  "004-00308D" );

  foreach ($values as $i => &$value) {
    if(ctype_alpha(substr($value,0,1))){
      if(strpos($value,'-')){
         $value = substr($value,0,(strpos($value, '-' )));
      }
    }
  }

Upvotes: 0

Vincent Decaux
Vincent Decaux

Reputation: 10714

This works, just test if first letter of second part is numeric :

$values = array(
    "PANELEGP00001",
    "PANELEGP00003",
    "PANELEGP00001-1",
    "PANELEGP00002-TOS",
    "PANELEGP00004-2",
    "LIVOR-44_900_2100",
    "004-00308D" 
);

foreach ($values as $i => &$value) {
    $words = explode('-', $value);

    // test if word contains "-"
    if (count($words) > 0) {
        // test first char of second part
        if (! is_numeric($words[1][0])) {
            // if first char is a letter, just keep first part
            $values[$i] = $words[0];
        }
    }
}

// $values contains correct rows
var_dump($values);

Upvotes: 2

Related Questions