找到-时删除php中的单词-

时间:2018-10-19 13:00:24

标签: php html

我有以下代码用来切词。如果在单词前面找到-,则将单词切掉,仅保留第一部分

<?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

?>

仅当我在开头PANELEGP00002-TOS这样找到一个字母,而不是在此004-00308D或这个004-0D3080中才找到字母时,才想剪切1}}

2 个答案:

答案 0 :(得分:2)

这有效,只需测试第二部分的首字母是否为数字即可:

$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);

答案 1 :(得分:0)

基于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, '-' )));
      }
    }
  }